Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 693
Kakar Avatar asked Mar 07 '14 18:03

Kakar


People also ask

What is choice field in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.

How do you make a field optional in Django?

Use null=True and blank=True in your model. Save this answer.

What is default in Django model?

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 CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.


2 Answers

Use the default attribute:

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

or

display = models.CharField(..., default=CHOICES[1][1])
like image 154
Drewness Avatar answered Sep 18 '22 18:09

Drewness


You could just set the default attribute:

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

Reference.

like image 26
signal Avatar answered Sep 17 '22 18:09

signal