在Django CMS中初始化MultipleChoiceField

时间:2014-05-09 19:18:38

标签: python django forms django-cms

我的模型中有一个CharFielddisplayed_fields),我在表单中显示为MultipleChoiceField。目前,即使模型displayed_fields非空,表单也会加载未选中任何内容。

我希望表单能够初始化为之前选择的项目。到目前为止,我已尝试将intial的不同值{}包括initial=ExamplePlugin.EMAIL_COLUMNinitial={'displayed_fields': ['name', 'office', 'phone']}添加到forms.py的字段声明中,而不是{39} ;似乎改变了什么。是否可以像这样初始化它,如果没有,是否有比CharField更好的模型?

models.py

class ExamplePlugin(CMSPlugin):
    NAME_COLUMN = 'name'
    OFFICE_COLUMN = 'office'
    PHONE_COLUMN = 'phone'
    EMAIL_COLUMN = 'email'
    TITLE_COLUMN = 'title'

    COLUMN_CHOICES = (
        (NAME_COLUMN, 'First and Last Name'),
        (OFFICE_COLUMN, 'Office Location'),
        (PHONE_COLUMN, 'Phone Number'),
        (EMAIL_COLUMN, 'Email Address'),
        (TITLE_COLUMN, 'Title'),
    )

    displayed_fields = models.CharField(blank=False, verbose_name='Fields to show', max_length=255)

forms.py

class ExampleForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)

    displayed_fields = MultipleChoiceField(choices=ExamplePlugin.COLUMN_CHOICES, help_text="Select columns that you would like to appear.")

    class Meta:
        model = ExamplePlugin

1 个答案:

答案 0 :(得分:2)

我认为你应该这样做:

class ExampleForm(ModelForm):
    displayed_fields = MultipleChoiceField(choices=ExamplePlugin.COLUMN_CHOICES, help_text="Select columns that you would like to appear.", initial=['name', 'office', 'phone'])

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)

    class Meta:
        model = ExamplePlugin

我认为MultipleChoiceField接受列表作为默认列表。