Cerin
Cerin

Reputation: 64709

MultipleChoiceField not showing stored values in Django Admin

How do you get a MultipleChoiceField() to correctly load initial values?

I have a Django model with a CharField, which I'm rendering in admin as a MultipleChoiceField() because I want to limit its value to one or more specific choices.

My code looks something like:

class MyModelInlineForm(ModelForm):

    my_text_field = forms.MultipleChoiceField(required=False)

    def __init__(self, *args, **kwargs):
        super(MyModelInlineForm, self).__init__(*args, **kwargs)

        self.fields['my_text_field'].choices = get_choices(self.instance)

        if self.instance:
            self.fields['my_text_field'].initial = self.instance.my_text_field

class MyModelInline(admin.TabularInline):
    model = MyModel
    form = MyModelInlineForm
    extra = 0

It seems to render fine, but when I select values and save, the new form loads with no values selected. I've confirmed the value is being correctly saved in the database, but the form isn't loading it, and I'm not sure why.

Based on some similar questions, I tried explicitly setting the initial value of my model's saved field, but this appeared to have no effect.

What am I doing wrong?

Upvotes: 5

Views: 2913

Answers (2)

Zoie
Zoie

Reputation: 354

You need to set the value in the form's initial (a dictionary)

def __init__(self, *args, **kwargs):
    super(MyModelInlineForm, self).__init__(*args, **kwargs)
    self.initial['my_text_field'] = eval(self.initial['my_text_field'])

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239250

You need to set the value in the form's initial (a dictionary), not the field's:

if self.instance:
    self.initial['my_text_field'] = self.instance.my_text_field

Upvotes: 5

Related Questions