开发者

Filter Objects in a Django Formset

I am using inlineformset_factory to generate a formset as so:

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)) 

I have two questions

  1. How can i restrict the Model2 objects so that not all applicable objects are present, but only a filtered subset?
  2. Does anyone have any example code for using class-based views with formsets?

Updated with functioning code answering question #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(开发者_StackOverflow中文版):
        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))


would this help? https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-queryset

basically, try using queryset kwarg when you create your formset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜