Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...