Reputation: 286
In my exercise I have a Django model of a book, having a field "genre". This field has the following option choices
GENRES_CHOICE = (
('ADV','Adventure'),
('FAN','Fantasy'),
('POE','Poetry'),
)
and the model field is
genre = models.CharField(max_length = 3, blank = False, choices = GENRES_CHOICE, db_index = True, editable = False)
In my template I would like to show to the user the list of the genres (Adventure, Fantasy, Poetry) and hava available the keys, in order to possibly use them as parameters.
In order to do so, I would like to have a function that returns the data structure GENRES_CHOICE, but I am not able to. How to solve this problem?
EDIT: more code details
appname= mybookshelf, file -> models/Book.py
# possible choices for the gerne field
GENRES_CHOICE = (
('ADV','Adventure'),
('FAN','Fantasy'),
('POE','Poetry'),
)
class Book(models.Model):
"""
This is the book model
...
## ATTRIBUTES (better use init, but in Django not always possible)
id = models.CharField(max_length = 64, blank = False, unique = True, primary_key = True, editable = False)
""" unique id for the element """
genre = models.CharField(max_length = 3, blank = False, choices = GENRES_CHOICE, db_index = True, editable = False)
""" book genre """
published_date = models.DateField(null = True, auto_now_add = True, editable = False)
""" date of publishing """
Then, into another file, lets say MyFunctions.py I have
from mybookshelf.models import GENRES_CHOICE
def getBookCategories():
"""
This function returns the possible book categories
categories = GENRES_CHOICE
return categories
Upvotes: 0
Views: 377
Reputation: 75
You could use the get_modelfield_display() method in your template, e.g.:
{{ book.get_genre_display }}
Upvotes: 0
Reputation: 2913
I am not 100% sure this is what you are after, but if you want to show the user the list of GENRES_CHOICE you can do this in your templete:
{% for choice_id, choice_label in genres %}
<p> {{ choice_id }} - {{ choice_label }} </p>
{% endfor %}
ofcourse pass GENRES_CHOICE as genres
Upvotes: 0
Reputation: 22808
views.py
from app_name.models import GENRES_CHOICE
def view_name(request):
...............
return render(request, 'page.html', {
'genres': GENRES_CHOICE
})
page.html
{% for genre in genres %}
{{genre.1}}<br/>
{% endfor %}
Upvotes: 3