Skip to content Skip to sidebar Skip to footer

How Do I Make A Django Modelform Menu Item Selected By Default?

I am working on a Django app. One of my models, 'User', includes a 'gender' field, as defined below: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender

Solution 1:

If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:

form = MyModelForm (initial={'gender':'M'})

-OR-

You can override certain attributes of a ModelForm using the declarative nature of the Forms API. However, this is probably a little cumbersome for this use case and I mention it only to show you that you can do it. You may find other uses for this in the future.

classMyModelForm(forms.ModelForm):
    gender = forms.ChoiceField (choices=..., initial='M', ...)
    classMeta:
        model=MyModel

-OR-

If you want a ModelForm that is bound to a particular instance of your model, you can pass an 'instance' of your model which causes Django to pull the selected value from that model.

form = MyModelForm (instance=someinst)

Solution 2:

Surely default will do the trick?

e.g.

gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)

Post a Comment for "How Do I Make A Django Modelform Menu Item Selected By Default?"