我的模型中有一个CharField
(displayed_fields
),我在表单中显示为MultipleChoiceField
。目前,即使模型displayed_fields
非空,表单也会加载未选中任何内容。
我希望表单能够初始化为之前选择的项目。到目前为止,我已尝试将intial
的不同值{}包括initial=ExamplePlugin.EMAIL_COLUMN
和initial={'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
答案 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接受列表作为默认列表。