Django - 使用多种表单 [英] Django - Working with multiple forms

查看:30
本文介绍了Django - 使用多种表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是在一个页面中管理多个表单,我知道有表单集,并且我知道表单管理是如何工作的,但是我的想法有一些问题.

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.

只是为了帮助您想象我的问题是什么,我将使用 django 示例模型:

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',) 

所以我想做的是在一个页面中包含 Poll 和 Choice 模型的多个表单实例,但请注意,这些模型也可以重复:

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>

如您所见,有两种 Poll 表单和一种 Choice 表单,但 Poll 表单由 Choice 表单分隔.我确实需要表单在页面中保持它们的顺序,所以使用表单集有点困难.

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.

我遇到的问题是,帖子中的值都以名称answer"命名,因此我以名称answer"获得了所有表单中所有元素的列表,但我无法识别哪些属于每种形式.

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?

感谢您的帮助!

PD:不要关注 Poll 和 Choice 之间的关系,那些模型只是为了澄清问题,所以关系根本不重要.

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.

推荐答案

使用 prefix kwarg

您可以将表单声明为:

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 会处理剩下的事情.

Django will handle the rest.

这样您就可以在页面上拥有任意数量的相同类型的表单

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

这篇关于Django - 使用多种表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆