[英]Django:What is wrong with my code?
These are my models: 这些是我的模型:
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')
And this is the view which handles creation of option: 这是处理选项创建的视图:
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}))
So when I submit the form to this view,I get the following error: 因此,当我向该视图提交表单时,出现以下错误:
Exception Type: IntegrityError
Exception Value: hit_option.warval_id may not be NULL
I know what this error is and why it is coming but how can I remove this error? 我知道此错误是什么,为什么会出现,但如何删除此错误?
As you realize, this is because you're not setting the foreign key value anywhere. 如您所知,这是因为您没有在任何地方设置外键值。 You probably want to use
inlineformset_factory
which will take care of setting the FK to the parent war
object for you. 您可能要使用
inlineformset_factory
,它将为您设置FK到父级war
对象。
Make warval a non-required field with 将warval设为非必填字段
class option(models.Model):
warval =models.ForeignKey(war, null=True)
value = models.CharField(max_length=10)
or define formset.warval before saving, make a default value... 或在保存之前定义formset.warval,并设置默认值...
edit: 编辑:
read here and here for using subset of fields on a form and saving. 在此处和此处阅读有关在表单上使用字段子集并进行保存的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.