4

我正在使用 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)) 

我有两个问题

  1. 如何限制 Model2 对象,以便不存在所有适用的对象,而只存在过滤的子集?
  2. 有没有人有任何使用基于类的视图和表单集的示例代码?

更新了功能代码回答问题 #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))
4

1 回答 1

8

这会有帮助吗?https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#sharing-the-queryset

基本上,在创建表单集时尝试使用 queryset kwarg。

于 2011-08-27T04:26:34.610 回答