Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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():
        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))
like image 970
Dave Avatar asked Feb 24 '23 04:02

Dave


1 Answers

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.

like image 93
akonsu Avatar answered Feb 26 '23 20:02

akonsu