我正在使用 inlineformset_factory 生成一个表单集,如下所示:
FormSet = inlineformset_factory(Model1, Model2, extra=0)
if request.method =="POST":
formset = FormSet(request.POST, instance=model1_object)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( reverse-blah )
else:
formset = PupsFormSet(instance=model1_object,)
return render_to_response("template.html", {"formset":formset, 'model1_object':model1_object},context_instance=RequestContext(request))
我有两个问题
- 如何限制 Model2 对象,以便不存在所有适用的对象,而只存在过滤的子集?
- 有没有人有任何使用基于类的视图和表单集的示例代码?
更新了功能代码回答问题 #1
FormSet = inlineformset_factory(Model1, Model2, extra=0)
if request.method =="POST":
formset = FormSet(request.POST, instance=model1_object, queryset=Model2.objects.filter(foo=bar))
if formset.is_valid():
formset.save()
return HttpResponseRedirect( reverse-blah )
else:
formset = PupsFormSet(instance=model1_object, queryset=Model2.objects.filter(foo=bar))
return render_to_response("template.html", {"formset":formset, 'model1_object':model1_object},context_instance=RequestContext(request))