我正在尝试用django制作一些表格。
我做了一些模特:
class Identity(models.Model):
[...]
class Move(models.Model):
identity = models.OneToOneField(Identity, blank=True)
[...]
观点:
def firstform(request):
forms = {}
if request.method == "POST":
forms["move_form"] = MoveForm(request.POST)
forms["identity_form"] = IdentityForm(request.POST)
if all((forms["move_form"].is_valid(),
forms["identity_form"].is_valid())):
forms["identity_form"].save()
forms["move_form"].identity = forms["identity_form"]
forms["move_form"].save()
return HttpResponse("OK")
else:
forms["move_form"] = MoveForm()
forms["identity_form"] = IdentityForm()
return (render(request, "main/devis.html", forms))
但是当我尝试提交表单时,我会收到django.db.utils.IntegrityError: NOT NULL constraint failed: main_move.identity_id
。
我怎么解决这个问题?
答案 0 :(得分:1)
我认为你需要明确地分配身份实例,而不是保存的形式:
identity = forms["identity_form"].save()
forms["move_form"].identity = identity
forms["move_form"].save()
答案 1 :(得分:0)
我找到了答案,我只需要在blank=True
课程中将null=True
替换为Move
。我的坏:这很愚蠢。
答案 2 :(得分:0)
当您调用表单的save()
方法时,它会返回实例。您应该将identity
分配给move
实例,而不是移动表单。
其次,在保存移动表单时使用commit=False
。这意味着该实例未保存到数据库中,因此您无法获得IntegrityError
。这样,如果您希望所有身份都有移动,您可以在模型中保留null=False
。
forms["move_form"] = MoveForm(request.POST)
forms["identity_form"] = IdentityForm(request.POST)
if all((forms["move_form"].is_valid(),
forms["identity_form"].is_valid())):
move = forms["move_form"].save(commit=False)
identity = forms["identity_form"].save()
move.identity = identity
move.save()
# It's usually a good idea to redirect here rather than
# returning a response
return HttpResponse("OK")