get_FOO_display method
When you use the choices option in your model, the data shown in a browser may be the key to the choices (not the human-readable name). The get_FOO_display
method can change it to the human-readable name.
FOO
is an often-used word as a placeholder for a value that can change. In the Django template context, it represents an object attribute that is defined in the model field with the choices option.
Practice
Objective:
Add a human-readable name to the choices option
In the LearningCourse model, 'level
' field is defined with the choices
option. We are adding a human-readable name for the field.
1. Add the object and attribute in a normal way
Add the yellow line of the code below into the course_list.html file, and save the file.
:
<p> {{ course.title|upper }}</p>
<p> {{ course.level }}</p>
:
Go to localhost:8000/employee-learning/course-list/. You can see only B or A, which are keys for the list for the choices option.
2. Add the get_Foo_display method
Replace the 'level
' part with 'get_level_display
'.
:
<p> {{ course.title|upper }}</p>
<p> {{ course.get_level_display }}</p>
:
Go to localhost:8000/employee-learning/course-list/. You can confirm that the list has changed to human-readable names.