在我的练习中,我有一本书的Django模型,有一个字段“类型”。该字段具有以下选项
GENRES_CHOICE = (
('ADV','Adventure'),
('FAN','Fantasy'),
('POE','Poetry'),
)
,模型字段为
genre = models.CharField(max_length = 3, blank = False, choices = GENRES_CHOICE, db_index = True, editable = False)
在我的模板中,我想向用户展示类型列表(冒险,幻想,诗歌)和hava可用键,以便可能将它们用作参数。
为了做到这一点,我想有一个返回数据结构GENRES_CHOICE的函数,但我无法做到。如何解决这个问题呢?
编辑: 更多代码详情
appname = mybookshelf,file - >模型/ 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 """
然后,进入另一个文件,让我说MyFunctions.py
from mybookshelf.models import GENRES_CHOICE
def getBookCategories():
"""
This function returns the possible book categories
categories = GENRES_CHOICE
return categories
答案 0 :(得分:2)
<强> 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 %}
答案 1 :(得分:0)
我不是100%确定这是你所追求的,但如果你想向用户显示GENRES_CHOICE列表,你可以在你的模板中执行此操作:
{% for choice_id, choice_label in genres %}
<p> {{ choice_id }} - {{ choice_label }} </p>
{% endfor %}
当然将GENRES_CHOICE作为流派传递
答案 2 :(得分:0)
您可以在模板中使用get_modelfield_display()方法,例如:
{{ book.get_genre_display }}