Asinox
Asinox

Reputation: 6865

Django: how to set the initial value of a ModelChoiceField?

I'm using a ModelChoiceField:

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

How can specify an initial value that is selected when the form is shown?

Upvotes: 77

Views: 96723

Answers (7)

Williams
Williams

Reputation: 4338

Django now allows the default initial value to be set by defining initial like other form fields except you set it to the id instead.

Now this will suffice:

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

Though both still work.

Upvotes: 12

Faizan Mustafa
Faizan Mustafa

Reputation: 401

    field1 = forms.ModelChoiceField(
        queryset=Model.objects.all(), 
        empty_label="Selected value")

Upvotes: 4

Pavel Shvedov
Pavel Shvedov

Reputation: 1314

You can just use

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

to make the first value selected etc. It's more generic than the other answer.

Upvotes: 32

Spenser Black
Spenser Black

Reputation: 385

Just want to add this answer after stumbling on this question. I know it works on Django 3.2, at least. If you have some calculated value in the __init__ method, you can do this to set the initial value at instantiation as well:

def __init__(self, value, *args, **kwargs):
    # super call, etc.
    self.do_something(value)
    self.fields['field'].initial = value

If the form does multiple things with value, it's a bit more DRY to pass it only once instead of redundantly with the initial kwarg in instantiation.

Upvotes: 0

Nguyễn Đức Tứ
Nguyễn Đức Tứ

Reputation: 61

The code

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

and

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

or initial field directly following:

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

All work.

The first two ways will override the final way.

Upvotes: 6

Peter Bob Ukonu
Peter Bob Ukonu

Reputation: 65

You could do this as well:

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

if you are parsing your primary key through a query string or via an ajax call no need for an instance, the query set has already handled that for your drop down, the pk indexes the state you want

Upvotes: -1

Michael Cheng
Michael Cheng

Reputation: 10501

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.

Upvotes: 113

Related Questions