在我的练习中,我有一本书的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,文件 - >型号/ 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
您是否使用modelform?或者你希望它直接显示在模板中? – catherine 2013-03-03 13:25:38
不,我没有使用模型,我想知道是否有可能“直接”显示模板中的数据。 – klebe85 2013-03-03 13:29:10
是的,这是可能的。只需拨打GENRES_CHOICE从模型到视图 – catherine 2013-03-03 13:31:25