Filter Objects in a Django Formset
Asked Answered
C

1

5

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))
Caledonian answered 26/8, 2011 at 16:11 Comment(0)
R
8

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.

Rocketry answered 27/8, 2011 at 4:26 Comment(1)
that works great... the queryset argument has to go in the formset = Formset() call not the inlineformset_factory call so i have updated my question with that answerCaledonian

© 2022 - 2024 — McMap. All rights reserved.