Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 805
Cerin Avatar asked Feb 28 '12 19:02

Cerin


1 Answers

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
like image 117
Chris Pratt Avatar answered Oct 15 '22 14:10

Chris Pratt