Django - 以一种形式重复表单字段n次

时间:2009-07-30 10:00:57

标签: python django django-forms

我有一个包含几个字段的Django表单,其中一个字段需要重复n次(其中n在设计时不知道)我将如何进行编码(如果可能的话)?

e.g。而不是: -

Class PaymentsForm(forms.form):
    invoice = forms.CharField(widget=ValueHiddenInput())
    total = forms.CharField(widget=ValueHiddenInput())
    item_name_1 = forms.CharField(widget=ValueHiddenInput())
    item_name_2 = forms.CharField(widget=ValueHiddenInput())
    .
    .
    .
    item_name_n = forms.CharField(widget=ValueHiddenInput())

我需要这样的东西: -

Class PaymentsForm(forms.form):
    invoice = forms.CharField(widget=ValueHiddenInput())
    total = forms.CharField(widget=ValueHiddenInput())
    item_name[n] = forms.CharField(widget=ValueHiddenInput())

谢谢,
理查德。

2 个答案:

答案 0 :(得分:8)

您可以在表单的__init__方法中创建重复的字段:

class PaymentsForm(forms.Form):
    invoice = forms.CharField(widget=forms.HiddenInput())
    total = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        super(PaymentsForm, self).__init__(*args, **kwargs)
        for i in xrange(10):
            self.fields['item_name_%d' % i] = forms.CharField(widget=forms.HiddenInput())

有关动态表单的更多信息,例如: here

编辑:回答评论中的问题:只需将重复次数作为__init__方法的参数,如下所示:

    def __init__(self, repetitions, *args, **kwargs):
        super(PaymentsForm, self).__init__(*args, **kwargs)
        for i in xrange(repetitions):
            self.fields['item_name_%d' % i] = forms.CharField(widget=forms.HiddenInput())

然后在您的视图中(或在您创建表单的任何位置):

payments_form = PaymentsForm(10)

答案 1 :(得分:4)

使用formsets