Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

default value for django choice field

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the default attribute:

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

or

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...