[Django]-DRY way to declare several similar form fields

4👍

You can use Django dynamic Form generation

from django import forms

class MyForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        for i in range(20):
            self.fields["file_%d" % i] = forms.FileInput()

See Docs here.

1👍

Use a loop:

files = [forms.FileInput() for i in range(20)]

Leave a comment