在Django Formset中过滤对象

时间:2011-08-26 16:11:37

标签: django django-forms formset django-class-based-views class-based-views

我正在使用inlineformset_factory来生成一个formset:

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. 有没有人有任何使用formset的基于类的视图的示例代码?
  3. 更新了功能代码回答问题#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))
    

1 个答案:

答案 0 :(得分:7)

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

基本上,在创建formset时尝试使用queryset kwarg。