title: Django dynamic forms - on-the-fly field population?
body: <p>I've been scanning through Django documentation, and Google search results, all afternoon and I'm still somewhat stuck in my attempt to create a dynamic form.  I'm hoping I just need someone to nudge me in the right direction :-)  I'm just starting to learn Django, so I'm still very much a beginner; however, I'm already an intermediate python user.</p>
  
  <p>What I'm trying to do is create a dynamic form, where the user makes a selection from a drop-down menu, and based on that selection another part of the form will automatically update to display results relevant to the currently selected item, but from another database table.</p>
  
  <p>I'll try and use a simplified version of the models from the Django tutorial to better illustrate what I'm trying to do:</p>
  
  <pre><code># models.py
  from django.db import models
  
  class Poll(models.Model):
      question = models.CharField(max_length=200)
  
  class Choice(models.Model):
      poll = models.ForeignKey(Poll)
      choice = models.CharField(max_length=200)
  </code></pre>
  
  <p>So lets say I want to have something like a drop-down selection field, populated with the question from each Poll in the database.  I also want to have a text-field, which displays the corresponding choices for the currently selected Poll, which will update on-the-fly whenever the user selects a different Pool.  I've been able to figure this out by placing a button, and posting information back to the form;  However, I'm trying to do this automatically as the user makes a selection.  My view sort of looks something like this at the moment:</p>
  
  <pre><code>#view.py
  from django import forms
  from django.shortcuts import render_to_response
  
  from myapp.models import Poll,Choice
  
  class MyModelChoiceField(forms.ModelChoiceField):
      def label_from_instance(self, obj):
          return "%s" % obj.question
  
  class PollSelectionForm(forms.Form):
      polls = MyModelChoiceField( queryset=Poll.objects.all() )
  
  class ChoiceResults(forms.Form):
      def __init__(self, newid, *args, **kwargs):
          super(ChoiceResults, self).__init__(*args, **kwargs)
  
          self.fields['choice'] = forms.TextField( initial="" )
  
  def main(request):
      return render_to_response("myapp/index.html", {
          "object": PollSelectionForm(), 
          "object2": ChoiceResults(),
      })
  </code></pre>
  
  <p>My template is very simple, just something like</p>
  
  <pre><code>{{ object }}
  {{ object2 }}
  </code></pre>
  
  <p>I'm sure the way I'm going about creating the forms is probably not the best either, so feel free to criticize that as well :-)  As I mentioned, I've read solutions involving reposting the form, but I want this to happen on-the-fly... if I can repost transparently then that would be fine I guess.  I've also seen libraries that will let you dynamically create forms, but that just seems like overkill.</p>