Empty / Default Option for ModelChoiceField in Django

Posted by: scoopseven 13 years, 2 months ago

UPDATE (8/4/2011): Where have you been all my life, empty_label? Of course, Django has a much cleaner non-javascript solution: def __init__(self, *args, **kwargs):     super(MyForm, self).__init__(*args, **kwargs)     self.fields['field1'].empty_label = 'Select Something'     self.fields['field2'].empty_label = 'Select Something Else' UPDATE (4/5/2011): When you do what I suggested in the original post, the default shows up, as expected, but it turns out you lose all of Django's automatic ability to deal with the ModelForm, so you have to do all of the form processing manually. Blah. A much better solution is to use jQuery: // django doesn't let us override the default value for ModelFormField: http://code.djangoproject.com/ticket/13769 // cheat with jQuery and setup the default options $("#id_firmtype option:eq(0)").replaceWith(""); $("#id_jobfunction option:eq(0)").replaceWith(""); $("#id_firmtype option:eq(0)").attr("selected", "selected"); $("#id_jobfunction option:eq(0)").attr("selected", "selected"); ORIGINAL POST: In an earlier post we figured out how to add a default option to a Django ChoiceField within a form (forms.Form). The same task is slightly different when we're dealing with a ModelChoiceField within an ModelForm (forms.ModelForm). This is a three-step process. First, in the ModelForm, we have to change the field to a ChoiceField manually: myformfield = forms.ChoiceField(choices=[ (x.id, x.description) for x in MyModel.objects.all()]) Then, you need to override the init function in your ModelForm (and you can modify the label too, if it pleases you) to insert a value that you can choose as the default when you instantiate the form: def __init__(self, *args, **kwargs):     super(MyModelForm, self).__init__(*args, **kwargs)     if not self.fields['myformfield'].choices[0][0] == '':         self.fields['myformfield'].choices.insert(0, (0,'Choose an Option') )     self.fields['myformfield'].label = "This is fun" Finally, when you instantiate the form, choose that default value you inserted in your init def: my_form = MyModelForm(prefix='somevalue', initial={'myformfield':0}) I've seen several different suggestions, but this is the only way that I could get this to function properly.

Current rating: 1

Recent Tweets

Recent Posts






RSS / Atom