在Django中使用formset_factory [英] Using formset_factory in Django
问题描述
我是Django的新用户,我使用以下代码生成表单
I'm a new user to Django, i use the following code to produce a form
class GetMachine(forms.Form):
Machine_Name = forms.CharField(max_length=20)
Number_of_lines = forms.IntegerField(max_value=10)
class GetLine(forms.Form):
Line_name = forms.CharField(max_length=20)
def install(request):
if request.method == 'POST':
form = GetMachine(request.POST)
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
form = GetLine()
return render_to_response('install.html', { 'form': form, })
else:
form = GetMachine() # An unbound form
return render_to_response('install.html', { 'form': form, })
如何修改上述代码,以便Number_of_lines用于创建n个Line_Name表单字段
How can modify the above code, such that the "Number_of_lines" is used to create n number of "Line_Name" form fields.
例如,如果Number_of_lines的值为2,我再次要求用户输入两行的名称为
For example, if the value of Number_of_lines is 2, I would again like to ask the user to enter the name of both the lines as
Line-1的名称:
Name of Line-1:
行2的名称:
推荐答案
从POST数据获取number_of_lines后,可以将该数字作为extra参数传递给formset工厂。
After you get the number_of_lines from the POST data, you can pass that number as the 'extra' parameter to the formset factory.
from django.forms.formsets import formset_factory
...
form = GetMachine(request.POST)
if form.is_valid(): # All validation rules pass
number_of_lines = form.cleaned_data['Number_of_lines']
GetLineFormSet = formset_factory(GetLine, extra=number_of_lines)
formset = GetLineFormset()
form = GetLine()
...
Protip:您还可以使用max_num参数将行数保持在合理的限制:
Protip: You can also use the max_num parameter to keep the number of lines to a reasonable limit:
GetLineFormSet = formset_factory(GetLine, extra=number_of_lines, max_num=10)
这篇关于在Django中使用formset_factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!