将内容保存到Django模型fai

2024-09-30 18:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图将表单内容保存到模型中,但最后总是出现三个错误,导致另一个错误

  1. editor.models.DoesNotExist: ContentModel matching query does not exist.
  2. sqlite3.IntegrityError: UNIQUE constraint failed: editor_contentmodel.ref_id
  3. django.db.utils.IntegrityError: UNIQUE constraint failed: editor_contentmodel.ref_id

型号.py

class ContentModel(models.Model):
    ref_id = models.CharField(primary_key=True, max_length=120, default='1', unique=True)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __str__(self):
        return self.content

    class Meta:
        unique_together = ("content", "ref_id")

视图.py

def index(request):
    template = "editor/home.html"

    try:
        json_content = ContentModel.objects.get(ref_id='1')
    except Exception:
        raise HttpResponseServerError

    if request.method == 'POST':
        form = ContentFormModel(request.POST)
        if form.is_valid():
            ref_id_new = '1'
            form_data = form.cleaned_data.get('content')
            new_content, created = ContentModel.objects.get_or_create(content=form_data)
            if created:
                new_content.ref_id = ref_id_new
                new_content.save()
    else:
        form = ContentFormModel()

    context = {'content': json_content.content, 'form': form}
    return render(request, template, context)

表单.py

class ContentFormModel(forms.ModelForm):
    class Meta:
        model = ContentModel
        fields = ['content']

我不确定代码有什么问题。你知道吗

是因为ref_id是主键吗?你知道吗

更新

我在python3上使用django1.10


Tags: pyformrefidtruenewgetif