Working with multiple forms on a single page in Django

177 Views Asked by At

I'm new to Django and I'm having a hard time wrapping my head around how to deal with "nested" forms in a template and how to process those forms accordingly. I'm creating a polling application similar to the tutorial, but more complex. I have multiple models (Poll, Question, Choice, Vote). A poll contains many questions, a question contains many choices.

I want to allow a user to view all the questions in a poll at once and vote on each question by selecting a choice from each question's choice set. After the user selects a choice for each question, they submit all their votes at once and process them to create the vote objects.

I'm really scratching my head at how to do this. Any help would be greatly appreciated.

Here are how my models are set up:

models.py

class Poll(models.Model):
    name = models.CharField(max_length=255, default="Unnamed Poll")
    key = models.CharField(max_length=16, blank=True, editable=False, unique=True, db_index=True, null=True)
    instructor = models.ForeignKey(User)
    course = models.ForeignKey(Course)
    active = models.BooleanField(default=False)
    anonymous = models.BooleanField(default=True, help_text="Allow votes to be anonymous?")

class Question(models.Model):
    question_text = models.CharField(max_length=255, verbose_name='Poll Question')
    poll = models.ForeignKey(Poll)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=255, verbose_name='Response Choice')

class Vote(models.Model):
    question = models.ForeignKey(Question)
    choice = models.ForeignKey(Choice)
    student = models.ForeignKey(User)
1

There are 1 best solutions below

0
Gautam Bhalla On

You should use django.forms.Formsets in your case.Read about formsets here

Please comment to ask for further clarifications.

cheers :-)