Django通过列表来创建Choices

时间:2018-11-06 18:05:39

标签: django django-forms choicefield

我想在具有从视图传递给它的列表中进行选择的表单上创建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函数来实现吗?

1 个答案:

答案 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