3👍
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
Source:stackexchange.com