Django - Repeating a form field n times in one form

前端 未结 2 1437
一个人的身影
一个人的身影 2021-02-03 14:39

I have a Django form with several fields in it one of which needs to be repeated n times (where n is not known at design time) how would I go about coding this (if it is possibl

相关标签:
2条回答
  • 2021-02-03 15:36

    You can create the repeated fields in the __init__ method of your form:

    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())
    

    More about dynamic forms can be found e.g. here

    edit: to answer the question in your comment: just give the number of repetitions as an argument to the __init__ method, something like this:

        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())
    

    and then in your view (or wherever you create the form):

    payments_form = PaymentsForm(10)
    
    0 讨论(0)
  • 2021-02-03 15:38

    Use formsets.

    0 讨论(0)
提交回复
热议问题