这些是我的模特:
class war(models.Model):
title = models.CharField(max_length=20)
class option(models.Model):
warval =models.ForeignKey(war)
value = models.CharField(max_length=10)
class warform(ModelForm):
class Meta:
model = war
class option_form(ModelForm):
class Meta:
model = option
exclude = ('warval')
这是处理选项创建的视图:
def warhandler(request,war_id):
f=modelformset_factory(option,form=option_form)
wobj=get_object_or_404(war,pk=war_id)
if request.method == 'POST':
formset = f(request.POST,queryset=option.objects.filter(warval=wobj))
if formset.is_valid():
formset.save()
return HttpResponse("Saved!check your model")
else:
return render_to_response("formset.html",RequestContext(request,{"set":formset}))
else:
formset = f(queryset=option.objects.filter(warval=wobj))
print(formset)
return render_to_response("formset.html",RequestContext(request,{"set":formset,"war":wobj}))
因此,当我将表单提交到此视图时,我收到以下错误:
Exception Type: IntegrityError
Exception Value: hit_option.warval_id may not be NULL
我知道这个错误是什么以及为什么会这样,但我怎么能删除这个错误?
答案 0 :(得分:2)
正如您所知,这是因为您没有在任何地方设置外键值。您可能希望使用inlineformset_factory
,它将负责为您设置FK到父war
对象。
答案 1 :(得分:1)