Making a list of form fields with a for loop?

I want to make a form that’s a list of all objects in a model with number inputs after them by using a for loop instead of typing out each field manually. How could this be accomplished? Thanks in advance to anyone who wants to respond.

What I’m trying to do:

class OrderForm(forms.Form):
    for p in [Model].objects.all():
        field = forms.IntegerField(label=p.product_text)

What I want to achieve in the view:

  • p: Integerfield
  • p: Integerfield
  • p: Integerfield
  • p: Integerfield
  • etc…

What I actually achieve:

  • last p in the model: Integerfield

As far as I’m aware you really want to use Formset and not to add various number of the same fields. However if not, then you can create a new class dynamically

OrderForm = type(
    'Form',
    (forms.Form,),
    {
        'p%s' % key: forms.IntegerField(label=p.product_text)
        for key, field in enumerate(Model.objects.all())
    },
)

but the fields must have different names.

In addition to the prior answer, you can also access the form fields attributes directly in the __init__ method of the class and add the fields there.

While it’s not a precise match, this earlier topic addressed a corresponding idea with the admin.