15

Suppose class Photo is to hold photos having choice fields and other attributes:

class Photo(models.Model):
    ONLYME = 'O'
    FRIENDS = 'F'
    PUBLIC = 'P'
    CHOICES = (
        (ONLYME, "Me"),
        (FRIENDS, "Friends"),
        (PUBLIC, "Public"),
    )

    display = models.CharField(max_length=1, choices=CHOICES, blank=True, null=True)
    user = models.ForeignKey(User)
    description = models.TextField()
    pub_date = models.DateTimeField(auto_now=True, auto_now_add=False)
    update = models.DateTimeField(auto_now=False, auto_now_add=True)
    image = models.ImageField(upload_to=get_upload_file_name, blank=True)

Now, how do I set the default or initial value of a photo to "Friends" in the display attribute?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Kakar
  • 5,354
  • 10
  • 55
  • 93

4 Answers4

23

Use the default attribute:

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

or

display = models.CharField(..., default=CHOICES[1][1])
Drewness
  • 5,004
  • 4
  • 32
  • 50
3

You could just set the default attribute:

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

Reference.

Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
signal
  • 200
  • 1
  • 2
  • 10
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
  • 11
  • 1
  • 3
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
  • 57,004
  • 12
  • 102
  • 110