Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use the "choices" field option in Django

I'm reading the tutorial here: https://docs.djangoproject.com/en/1.5/ref/models/fields/#choices and i'm trying to create a box where the user can select the month he was born in. What I tried was

 MONTH_CHOICES = (     (JANUARY, "January"),     (FEBRUARY, "February"),     (MARCH, "March"),     ....     (DECEMBER, "December"), )  month = CharField(max_length=9,                   choices=MONTHS_CHOICES,                   default=JANUARY) 

Is this correct? I see that in the tutorial I was reading, they for some reason created variables first, like so

FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' 

Why did they create those variables? Also, the MONTHS_CHOICES is in a model called People, so would the code I provided create a "Months Choices) column in the database called called "People" and would it say what month the user was born in after he clicks on of the months and submits the form?

like image 364
SilentDev Avatar asked Sep 07 '13 17:09

SilentDev


People also ask

How do you define choice fields in Django?

Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.

How do you make a field optional in Django?

You would have to add blank=True as well in field definition. If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True. Don't forget to reset and sync DB again after changing this.


1 Answers

I think no one actually has answered to the first question:

Why did they create those variables?

Those variables aren't strictly necessary. It's true. You can perfectly do something like this:

MONTH_CHOICES = (     ("JANUARY", "January"),     ("FEBRUARY", "February"),     ("MARCH", "March"),     # ....     ("DECEMBER", "December"), )  month = models.CharField(max_length=9,                   choices=MONTH_CHOICES,                   default="JANUARY") 

Why using variables is better? Error prevention and logic separation.

JAN = "JANUARY" FEB = "FEBRUARY" MAR = "MAR" # (...)  MONTH_CHOICES = (     (JAN, "January"),     (FEB, "February"),     (MAR, "March"),     # ....     (DEC, "December"), ) 

Now, imagine you have a view where you create a new Model instance. Instead of doing this:

new_instance = MyModel(month='JANUARY') 

You'll do this:

new_instance = MyModel(month=MyModel.JAN) 

In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.

like image 77
JCJS Avatar answered Sep 26 '22 15:09

JCJS