【问题标题】:How to use Django form fields multiple times in a GET or POST如何在 GET 或 POST 中多次使用 Django 表单字段
【发布时间】:2012-10-01 15:51:39
【问题描述】:
这是我所拥有的,一个简单的 Django 表单
class survey (forms.Form):
answer = forms.ChoiceField(
widget = RadioSelect(),
choices = answers_select
)
现在,在我的 HTML 页面上,我得到的不仅仅是一个问题,而是很多问题!是否可以将上述answer 字段用于所有问题?对于所有问题,我必须展示的只是相同的选择!
假设我有 3 个问题:
- 我的餐厅怎么样
- 食物怎么样
- 服务怎么样
上述answer 字段的选项为1. good, 2. bad 3. worst
所以,我不想为这 3 个问题创建 3 个表单字段,因为它是多余的
【问题讨论】:
标签:
python
django
django-forms
django-templates
【解决方案1】:
退后一步,想清楚 - 你需要 3 个ChoiceField 来跟踪 3 个单独问题的答案,而且没有办法绕过它。
实际上重复表单域构造调用是多余的,尤其是在处理 20 个问题时。在这种情况下,您可以将问题列表存储为类不变量,并在表单构建期间动态创建表单字段,而不是静态构建这些字段。
这里有一些东西可以让你初步了解如何去做:
class SurveyForm(forms.Form):
questions = _create_questions('How is my restaurant?',
'How is the Food?',
'How is the service?')
def __init__(self, *args, **kwargs):
# Create the form as usual
super(SurveyForm, self).__init__(*args, **kwargs)
# Add custom form fields dynamically
for question in questions:
self.fields[question[0]] = forms.ChoiceField(label=question[1],
widget=forms.RadioSelect(),
choices=answers_select)
@classmethod
def _create_questions(cls, *questions):
return [(str(index), question) for index, question in enumerate(questions)]
【解决方案2】:
您正在寻找formsets。你可以这样做:
from django.forms.formsets import formset_factory
SurveyFormSet = formset_factory(survey, extra=3, max_num=3)
将其添加到您的上下文中:
def get_context_data(self, request, *args, **kwargs):
data = super(MyView, self).get_context_data(request, *args, **kwargs)
data['formset'] = SurveyFormSet()
return data
然后在模板中使用:
<form method="post" action="">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
</form>
在发帖期间,您需要将 request.POST 和 request.FILES 传递给表单集构造函数:
formset = SurveyFormSet(request.POST, request.FILES)
链接的文档中对此进行了详尽的描述。