我的模型中有一个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
我猜MultipleChoiceField接受一个列表作为默认列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句