我想在具有从视图传递给它的列表中进行选择的表单上创建ChoiceField。
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)
不确定如何使用init函数来实现吗?
答案 0 :(得分:1)
上面的方法不起作用,因为您在此处定义的choices
将在构造 class 时从名为choices
的变量中获取。
但是您可以生成:
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))
]/code>
You thus then construct an OrderForm
and pass a list (or any iterable of strings) through the products
parameter, like:
OrderForm