在Django CMS中初始化MultipleChoiceField
我在我的模型里有一个叫做 CharField
的字段(displayed_fields
),我在表单中把它显示为一个 MultipleChoiceField
。现在,表单加载时没有任何选项被选中,即使模型里的 displayed_fields
不是空的。
我希望表单能自动选中之前选择的项目。目前,我尝试了不同的 initial
值,比如 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
1 个回答
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这个东西,默认情况下是可以接受一个列表的,我想是这样的。