python Django - 使用多种表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2374224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django - Working with multiple forms
提问by FernandoEscher
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:
只是为了帮助您想象我的问题是什么,我将使用 django 示例模型:
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:
所以我想要做的是在一个页面中有几个 Poll 和 Choice 模型的表单实例,但请注意,这些模型也可以重复:
<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.
如您所见,有两种 Poll 表单和一种 Choice 表单,但 Poll 表单由 Choice 表单分隔。我确实需要表单在页面中保持它们的顺序,所以使用表单集有点困难。
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.
我遇到的问题是,帖子中的值都以名称“answer”命名,因此我从名称为“answer”的所有表单中获取了所有元素的列表,但我无法确定哪些属于到每个表格。
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.
PD:不要关注Poll和Choice之间的关系,那些模型只是为了澄清问题,所以关系根本不重要。
回答by Zach
Use the prefix
kwarg
使用prefix
夸格
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.
Django 将处理剩下的事情。
This way you can have as many forms of the same type as you want on the page
通过这种方式,您可以在页面上拥有任意数量的相同类型的表单