动态地(并且干净地)向Django表单添加字段

时间:2010-05-31 08:44:27

标签: django forms dynamic

嘿伙计们,我知道这个问题已被提出过多次,但我还没有完全实现。正如您在下面看到的,我有一个表单,我可以动态地告诉您要创建多少行。 如何创建一个“添加行”链接,告诉视图要创建多少行?我真的很想在不增加网址的情况下这样做...

# 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>

2 个答案:

答案 0 :(得分:11)

当您的表单包含可变行数时,您需要的是formset

答案 1 :(得分:0)

11 年后!!!

我想动态地向表单添加一个 -not-so-important 标志,而不需要为此任务创建一个特定的表单。这是我如何处理我的案子

class CreateFooView(generic.CreateView):  
   ... 
   def get_form(self, form_class=None):
       form = super().get_form(form_class=self.form_class)
       ...
       field = forms.BooleanField(label="Add to Bar",required=False)
       form.fields['add_to_bar'] = field
       return form