简体   繁体   中英

Initializing a MultipleChoiceField in Django CMS

I have a CharField ( displayed_fields ) in my model that I display in my form as a MultipleChoiceField . Currently, the form loads with nothing selected, even if the model's displayed_fields is non-empty.

I'd like the form to initialize to the previously selected items being selected. So far, I've tried addint different values of intial , including initial=ExamplePlugin.EMAIL_COLUMN and initial={'displayed_fields': ['name', 'office', 'phone']} , to forms.py 's field declaration, which doesn't seem to change anything. Is it possible to initialize it like this, and if not, is there a better model to be using than 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

I think you should do:

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 accepts a list as its default, I guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM