Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so selected="selected" for this item.)

like image 987
RexE Avatar asked Mar 08 '09 20:03

RexE


People also ask

How do I customize Modelan in django?

To create ModelForm in django, you need to specify fields. Just associate the fields to first_name and lastName. Under the Meta class you can add : fields = ['first_name','lastName']. @Shishir solution works after I add that line. or you can try solution in Jihoon answers by adding vacant fields.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is default model django?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is form Is_valid () in django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.


2 Answers

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.

class MyModelForm (forms.ModelForm):
    gender = forms.ChoiceField (choices=..., initial='M', ...)
    class Meta:
        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)
like image 197
Joe Holloway Avatar answered Nov 09 '22 02:11

Joe Holloway


Surely default will do the trick?

e.g.

gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)
like image 20
John Montgomery Avatar answered Nov 09 '22 03:11

John Montgomery