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?
The above will not work, since the
choices
you here define will be taken from a variable namedchoices
at construction of the class.You can however generate:
You thus then construct an
OrderForm
and pass a list (or any iterable of strings) through theproducts
parameter, like: