Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Working with multiple forms

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.

like image 264
FernandoEscher Avatar asked Mar 03 '10 19:03

FernandoEscher


People also ask

Can we create multiple models in django?

Creating ModelsA project can contain multiple apps. An app can be in multiple projects. We will create two models: Question and Choice.

Can you have multiple forms on an HTML page?

Yes, we can use multiple tags inside one single HTML page. Sometimes we need to submit two distinct data from a single HTML page. To do so we need to use multiple tags.


1 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

like image 123
Zach Avatar answered Oct 06 '22 22:10

Zach