Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, ModelChoiceField() and initial value

I'm using something like this:

field1 = forms.ModelChoiceField(queryset=...)

How can I make my form show the a value as selected?

like image 902
Asinox Avatar asked Aug 26 '09 19:08

Asinox


2 Answers

If you want to set the default initial value you should be defining initial like other form fields except you set it to the id instead.

Say you've got field1 like this:

class YourForm(forms.Form):
    field1 = forms.ModelChoiceField(queryset = MyModel.objects.all() )

then you need to set initial when you create your form like this:

form = YourForm(initial = {'field1': instance_of_mymodel.pk })

rather than:

form = YourForm(initial = {'field1': instance_of_mymodel })

I'm also assuming you've defined __unicode__ for your models so this displays correctly.

like image 137
Michael Cheng Avatar answered Nov 06 '22 02:11

Michael Cheng


You can just use

 field1 = forms.ModelChoiceField(queryset=..., initial=0) 

to make the first value selected etc. It's more generic way, then the other answer.

like image 28
Pavel Shvedov Avatar answered Nov 06 '22 01:11

Pavel Shvedov