Django pass list to form to create Choices

2.6k Views Asked by At

I want to create a ChoiceField on a form that has choices from a list passed to it by a view.

from django import forms

class OrderForm(forms.Form):
    product_choices = []

    def __init__(self, products=None, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        if products:
            print(products)
            choices = enumerate(products)

    product_name = forms.ChoiceField(label='Product', choices=choices)

Not sure how to use the init function to achieve this?

1

There are 1 best solutions below

10
On

The above will not work, since the choices you here define will be taken from a variable named choices at construction of the class.

You can however generate:

from django import forms

class OrderForm(forms.Form):
    
    product_name = forms.ChoiceField(label='Product', choices=[])

    def __init__(self, products=None, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        if products:
            self.fields['product_name'].choices = [
                (str(k), v)
                for k, v in enumerate(products))
            ]

You thus then construct an OrderForm and pass a list (or any iterable of strings) through the products parameter, like:

def some_view(request):
    form = OrderForm(products=['product A', 'product B'])
    # ...
    # return some HttpResponse