Django – Working with multiple forms

Question:

What I’m trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind.

Just to help you to imagine what my problem is I’m going to use the django example models:

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

Now, imagine I’ve already made the form clases:

from django import forms
from mysite.polls.models import Poll, Choice

class PollForm(forms.ModelForm):
    class Meta:
        model = Poll

class ChoiceForm(forms.ModelForm):
    class Meta:
        model = Choice
        exclude = ('poll',) 

So what I want to do is to have several form instances of the Poll and Choice model in a single page, but mind that these models can be repeated too:

<form action="{{url}}" method="post">
    {{pollform}}
    {{choiceform}}
    {{pollform}}
</form>

As you can see there are two Poll forms and one Choice form, but the Poll forms are separated by the Choice form. I do need that the forms keep their order in the page, so is a little harder to use formsets.

The problem I got, is that the values that comes in the post are all by the name “answer”, so I get a list of all the elements from all forms by the name “answer” and I can’t identify which ones belong to each form.

Don’t know if this explanation get a clear view of my problem. Any ideas to get this stuff done?

Thanks for your help!

PD: Don’t pay attention to the relation between Poll and Choice, those models are just to clarify the problen, so the relation doesn’t matter at all.

Asked By: FernandoEscher

||

Answers:

Use the prefix kwarg

You can declare your form as:

form = MyFormClass(prefix='some_prefix')

and then, as long as the prefix is the same, process data as:

form = MyFormClass(request.POST, prefix='some_prefix')

Django will handle the rest.

This way you can have as many forms of the same type as you want on the page

Answered By: Zach
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.