【问题标题】:Initializing a MultipleChoiceField in Django CMS在 Django CMS 中初始化 MultipleChoiceField
【发布时间】:2014-05-09 19:18:37
【问题描述】:

我的模型中有一个CharField (displayed_fields),我在我的表单中显示为MultipleChoiceField。目前,即使模型的displayed_fields 不为空,表单也会在未选择任何内容的情况下加载。

我希望表单初始化为之前选择的项目。到目前为止,我已经尝试将intial 的不同值(包括initial=ExamplePlugin.EMAIL_COLUMNinitial={'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

【问题讨论】:

    标签: python django forms django-cms


    【解决方案1】:

    我认为你应该这样做:

    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 接受一个列表作为它的默认值,我猜。

    【讨论】:

    • 嗯,初始化时仍然没有选定的字段。你的意思是把displayed_fields的声明放在__init__下面,还是因为我一开始不小心把它放在了问题里?
    • @MiloPrice 对不起。它不应该进入 __init__。修好了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多