向Django添加字段动态(和干净地) [英] Adding fields to Django form dynamically (and cleanly)
本文介绍了向Django添加字段动态(和干净地)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#views.py
def myView(request):
如果request.method ==POST:
form = MyForm (request.POST,num_rows = 1)
如果form.is_valid():
返回render_to_response('myform_result.html',context_instance = RequestContext(request))
else:
form = MyForm(num_rows = 1)
返回render_to_response('myform.html',{'form':form},context_instance = RequestContext(request))
#forms.py
class MyForm(forms.Form):
def __init __(self,* args,** kwargs):
num_rows = kwargs.pop(' num_rows',1)
super(MyForm,self).__ init __(* args,** kwargs)
用于范围中的行(0,num_rows):
field = forms .CharField(label =Row)
self.fields [str(row)] = field
#myform.html http://example.com/myform
< form action =。 method =POSTaccept-charset =utf-8>
< ul>
{%表单中的字段%}
< li style =margin-top:.25em>
< span class =normal> {{field.label}}< / span>
{{field}}
< span class =formError> {{field.errors}}< / span>
< / li>
{%endfor%}
< / ul>
< input type =submitvalue =保存>
< / form>
< a href =ADD_ANOTHER_ROW?> + Add Row< / a>
解决方案
当您有一个可变行数的表单您需要的是表单。
Hey guys, I know this question has been brought up numerous times, but I'm not quite getting the full implementation. As you can see below, I've got a form that I can dynamically tell how many rows to create. How can I create an "Add Row" link that tells the view how many rows to create? I would really like to do it without augmenting the url...
# views.py
def myView(request):
if request.method == "POST":
form = MyForm(request.POST, num_rows=1)
if form.is_valid():
return render_to_response('myform_result.html', context_instance=RequestContext(request))
else:
form = MyForm(num_rows=1)
return render_to_response('myform.html', {'form':form}, context_instance=RequestContext(request))
# forms.py
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
num_rows = kwargs.pop('num_rows',1)
super(MyForm, self).__init__(*args, **kwargs)
for row in range(0, num_rows):
field = forms.CharField(label="Row")
self.fields[str(row)] = field
# myform.html http://example.com/myform
<form action="." method="POST" accept-charset="utf-8">
<ul>
{% for field in form %}
<li style="margin-top:.25em">
<span class="normal">{{ field.label }}</span>
{{ field }}
<span class="formError">{{ field.errors }}</span>
</li>
{% endfor %}
</ul>
<input type="submit" value="Save">
</form>
<a href="ADD_ANOTHER_ROW?">+ Add Row</a>
解决方案
When you have a form with a variable number of rows, what you need is a formset.
这篇关于向Django添加字段动态(和干净地)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文