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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With