title: Django/AJAX - Chained modelform selects - Fixing 'Select a Valid Choice' error without preloading of all possible choices
body: <p>I have these models:</p>
  
  <pre><code>class Subject(models.Model):
      title = models.CharField(max_length=255)
  
  class Teacher(models.Model):
      name = models.CharField(max_length=255)
      subjects = models.ManyToManyField(Subject)
  
  class Exam(models.Model):
      classroom = models.CharField(max_length=20)
      teacher = models.ForeignKey(Teacher)
      subjects = models.ManyToManyField(Subject)
  </code></pre>
  
  <p>So, since there are couple of thousands subjects, but only few of them are valid for a specific teacher, I'm disabling the subjects field in the modelform and once the teacher is selected, reenabling it and loading the possible options via AJAX. </p>
  
  <p>When editing an existing exam, everything is alright since I can do this:</p>
  
  <pre><code>if not self.instance._state.adding:
      self.fields['subjects'].queryset = self.instance.teacher.subject_set.all()
  </code></pre>
  
  <p>But, when I want to add a new exam, loading becomes very slow since all the possible options are loaded and only then my javascript can replace them with a narrower queryset. So, I tried to remove redundant loading like this:</p>
  
  <pre><code>if not self.instance._state.adding:
      self.fields['subjects'].queryset = self.instance.teacher.subject_set.all()
  else:
      self.fields['subjects'].queryset = Subject.objects.none()
  </code></pre>
  
  <p>Then I get a "Select a Valid Choice. XXX is not one of the available choices" error.</p>
  
  <p>So, is there a way to dynamically alter the queryset parameter of a specific field (or some other workaround) and avoid getting the specified error?</p>
  
  <h1>EDIT:</h1>
  
  <p>Alright, it seems I'm not able to explain my problem properly, since nobody's answering, so here's the complete code of a simplified app so you can try it for yourselves and see what's the problem.</p>
  
  <p><em>models.py</em></p>
  
  <pre><code>class Subject(models.Model):
      title = models.CharField(max_length=255)
  
      def __unicode__(self):
          return self.title
  
  class Teacher(models.Model):
      name = models.CharField(max_length=255)
      subjects = models.ManyToManyField(Subject)
  
      def __unicode__(self):
          return self.name
  
  class Exam(models.Model):
      classroom = models.CharField(max_length=20)
      teacher = models.ForeignKey(Teacher)
      subjects = models.ManyToManyField(Subject)
  
      def __unicode__(self):
          return u"{0} - {1}".format(self.classroom, self.teacher)
  </code></pre>
  
  <p><em>forms.py/admin.py</em></p>
  
  <pre><code>from .models import Subject, Teacher, Exam
  
  class ExamForm(forms.ModelForm):
      class Meta:
          model = Exam
          fields = ['classroom','teacher','subjects']
  
      class Media:
          js = (
              'https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js',
              'js/exam_form.js',
          )
  
      def __init__(self, *args, **kwargs):
          super(ExamForm, self).__init__(*args, **kwargs)
  
          if not self.instance._state.adding:
              self.fields['subjects'].queryset = self.instance.teacher.subjects.all()
          else:
              self.fields['subjects'].queryset = Subject.objects.none()
  
  @admin.register(Exam)
  class ExamAdmin(admin.ModelAdmin):
      list_display = ['classroom','teacher']
      form = ExamForm
  
  admin.site.register(Subject)
  admin.site.register(Teacher)
  </code></pre>
  
  <p><em>views.py</em></p>
  
  <pre><code>from .models import Teacher
  
  
  def query_teacher_subject(request):
      id = request.GET.get('id')
      if request.is_ajax():
          try:
              teacher = Teacher.objects.get(id=id)
          except Teacher.DoesNotExist:
              return HttpResponse(serializers.serialize('json', 'Teacher does not exist.'))
          else:
              return HttpResponse(serializers.serialize('json',teacher.subjects.all(), fields=('id','title',)))
      else:
          raise Http404
  </code></pre>
  
  <p><em>exam_form.js</em></p>
  
  <pre><code>$(function() {
      var t = $("#id_teacher");
      t.change(function(){
          if (t.val() != '') {
              $("#id_subjects").prop('disabled',false);
  
              var selected = [];
              $("#id_subjects :selected").each(function(i, sel){
                  selected.push($(sel).val());
              });
  
              $.get('/ajax-call/', {id:t.val()}, function(data) {
                  data = $.parseJSON(data);
                  var options;
                  $.each(data, function(index,item) {
                      options += '&lt;option value="' + item.pk + '"&gt;' + item.fields.title + '&lt;/option&gt;';
                  });
                  $("#id_subjects").html(options);
  
                  $("#id_subjects option").each(function(i, sel) {
                      if ($.inArray(sel.value, selected) !== -1) {
                          $('#id_subjects option[value=' + sel.value + ']').attr('selected', true);
                      }
                  });
  
              });
          } else {
              $("#id_subjects").prop('disabled',true);
          }
      });
      $("#id_teacher").trigger('change');
  });
  </code></pre>
  
  <p>So, if you omit the else branch in the <strong>init</strong> method of the ExamForm everything works fine except for the fact that ALL OF THE subjects get initially loaded. But, if you leave it there, then you get the following error: "Select a valid choice. 1 is not one of the available choices."</p>
  
  <p>So, how do I put initially empty queryset into a modelform that I would later populate via AJAX and still successfully validate?</p>