我一直试图将表单内容保存到模型中,但最后总是出现三个错误,导致另一个错误
editor.models.DoesNotExist: ContentModel matching query does not exist.
sqlite3.IntegrityError: UNIQUE constraint failed: editor_contentmodel.ref_id
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
我的回答是:
删除
default=1
和new_content.ref_id = ref_id_new
。因为ref_id
是主键,所以每次创建新行时,django都会为ref_id
列指定唯一的值。你不必自己动手。你知道吗相关问题 更多 >
编程相关推荐