title: Django filter ModelFormSet field choices... different from limiting the Formset's queryset
body: <p>I understand that it is possible to <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-custom-queryset" rel="nofollow noreferrer">override the default queryset 'used' by the modelformset</a>. This just limits the objects for which a form is created.</p>
  
  <p>I also found a Stack Overflow question about <a href="https://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform">filtering ForeignKey choices in a Django ModelForm</a>, but not a ModelForm <strong>Set</strong> and about <a href="https://stackoverflow.com/questions/1129759/limiting-available-choices-in-a-django-formset">limiting available choices in a Django formset</a>, but not a <strong>Model</strong> FormSet. I have included my version of this code below.</p>
  
  <p>What I want to do is render a ModelFormSet, for a school class ('teachinggroup' or 'theclass' to avoid clashing with the 'class' keyword) with one field limited by a queryset. This is for a teacher's class-editing form, to be able to reassign pupils to a different class, but limited to classes within the same cohort.</p>
  
  <p>My models.py</p>
  
  <pre><code>class YearGroup(models.Model):
      intake_year = models.IntegerField(unique=True)
      year_group = models.IntegerField(unique=True, default=7)
      def __unicode__(self):
          return u'%s (%s intake)' % (self.year_group, self.intake_year)
  
      class Meta:
          ordering = ['year_group']
  
  class TeachingGroup(models.Model):
      year = models.ForeignKey(YearGroup)
      teachers = models.ManyToManyField(Teacher)
      name = models.CharField(max_length=10)
      targetlevel = models.IntegerField()
      def __unicode__(self):
          return u'Y%s %s' % (self.year.year_group, self.name)
  
      class Meta:
          ordering = ['year', 'name']
  </code></pre>
  
  <p>My views.py</p>
  
  <pre><code>def edit_pupils(request, teachinggroup):
      theclass = TeachingGroup.objects.get(name__iexact = teachinggroup)
      pupils = theclass.pupil_set.all()
  
      PupilModelFormSet = modelformset_factory(Pupil)
  
      classes_by_year = theclass.year.teachinggroup_set.all()
      choices = [t for t in classes_by_year]
  #    choices = [t.name for t in classes_by_year] #### I also tried this
  
      if request.method == 'POST':
          formset = PupilModelFormSet(request.POST,queryset=pupils)
          if formset.is_valid():
              formset.save()
              return redirect(display_class_list, teachinggroup = teachinggroup)
      else:
          formset = PupilModelFormSet(queryset=pupils)
          for form in formset:
              for field in form:
                  if 'Teaching group' == field.label:
                      field.choices = choices
  
  
      return render_to_response('reassign_pupils.html', locals())
  </code></pre>
  
  <p>As you can see, I am limiting the choices to the queryset classes_by_year, which is only classes which belong to the same year group. This queryset comes out correctly, as you can see in the rendered page below, but it doesn't affect the form field at all.</p>
  
  <p>My template</p>
  
  <pre><code>{% for form in formset %}
  &lt;tr&gt;
      {% for field in form.visible_fields %}
      &lt;td&gt;            {# Include the hidden fields in the form #}
          {% if forloop.first %}
              {% for hidden in form.hidden_fields %}
              {{ hidden }}
              {% endfor %}
          {% endif %}
          &lt;p&gt;&lt;span class="bigtable"&gt;{{ field }}&lt;/span&gt;
          {% if field.errors %}
              &lt;p&gt;&lt;div class="alert-message error"&gt;
              {{field.errors|striptags}}&lt;/p&gt;
              &lt;/div&gt;
          {% endif %}
      &lt;/td&gt;
      {% endfor %}
  &lt;/tr&gt;
  {% endfor %}
  &lt;/table&gt;
  &lt;input type="submit" value="Submit changes"&gt;&lt;/p&gt;
  &lt;/form&gt;
  {{ choices }} &lt;!-- included for debugging --&gt;
  </code></pre>
  
  <p>The page renders with all teaching groups (classes) visible in the select widget, but the tag at the bottom of the page renders as: <code>[&lt;TeachingGroup: Y8 82Ma2&gt;, &lt;TeachingGroup: Y8 82Ma3&gt;]</code>, accurately showing only the two classes in Year 8.</p>
  
  <p>Note that I've also read through James Bennett's post <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/" rel="nofollow noreferrer">So you want a dynamic form</a> as recommended by <a href="https://stackoverflow.com/questions/1738952/how-can-i-limit-the-available-choices-for-a-foreign-key-field-in-a-django-modelfo">How can I limit the available choices for a foreign key field in a django modelformset?</a>, but that involves modifying the <code>__init__</code> method in forms.py, and yet the only way I know how to create a ModelFormSet is with modelformset_factory, which doesn't involve defining any classes in forms.py.</p>
  
  <p>Further to help from <a href="https://stackoverflow.com/users/199176/luke-sneeringer">Luke Sneeringer</a>, here is my new forms.py entry. After reading <a href="https://stackoverflow.com/questions/3429084/why-do-i-get-an-object-is-not-iterable-error">Why do I get an object is not iterable error?</a> I realised that some of my problems came from giving a tuple to the field.choices method, when it was expecting a dictionary. I used the .queryset approach instead, and it works fine:</p>
  
  <pre><code>class PupilForm(forms.ModelForm):
      def __init__(self, *args, **kwargs):
          super(PupilForm, self).__init__(*args, **kwargs)
          thepupil = self.instance
          classes_by_year = thepupil.teaching_group.year.teachinggroup_set.all()
          self.fields['teaching_group'].queryset = classes_by_year
  
  class Meta:
      model = Pupil
  </code></pre>