[Fixed]-Default value for Django choices field

23👍

Use the default attribute:

display = models.CharField(..., default=FRIENDS)

or

display = models.CharField(..., default=CHOICES[1][1])

3👍

You could just set the default attribute:

display = models.CharField(default='F', max_length=1, choices=CHOICES, blank=True, null=True)

Reference.

👤signal

0👍

There is a ChoiceField attribute for RadioButtons, then the solution could be with "initial" attribute… Example:

from django import forms
        CHOICES = [("1", "First choice"), ("2", "Second choice")]
    
    class ContactForm(forms.Form):
        choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, initial="1")
👤locika

0👍

Note that this is an old question. As of Django 3.0 the canonical way is to use the models.TextChoices class.

The following is an example that uses the Enum functional api:

CHOICES = models.TextChoices(
    "Display", (
        ("O", "Me"),
        ("F", "Friends"),
        ("P", "Public"),
    )
)

You can then write

display = models.CharField(
    max_length=1, choices=CHOICES, default=CHOICES.F, blank=True, null=True
)
👤Selcuk

Leave a comment