我的模型中有一个CharField
(displayed_fields
),我在我的表单中显示为MultipleChoiceField
。目前,表单加载时没有选择任何内容,即使模型的displayed_fields
是非空的。
我希望表单初始化为先前选择的项目被选中。到目前为止,我已经尝试添加intial
的不同值,包括initial=ExamplePlugin.EMAIL_COLUMN
和initial={'displayed_fields': ['name', 'office', 'phone']}
,到forms.py
的字段声明,这似乎没有改变任何东西。是否有可能像这样初始化它,如果不是,是否有比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
我认为你应该这样做:
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
multiechoicefield接受列表作为默认值,我猜