0

私の演習では、フィールド「ジャンル」を持つ本の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)

私のテンプレートでは、ジャンル (アドベンチャー、ファンタジー、詩) のリストをユーザーに表示し、利用可能なキーをパラメーターとして使用できるようにしたいと考えています。

そのためには、データ構造 GENRES_CHOICE を返す関数が必要ですが、できません。この問題を解決するには?

編集:コードの詳細

appname= mybookshelf、ファイル -> 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 """

次に、別のファイルに、私が持っている MyFunctions.py としましょう

from mybookshelf.models import GENRES_CHOICE 

    def getBookCategories():
        """
        This function returns the possible book categories 

        categories = GENRES_CHOICE 

        return categories
4

3 に答える 3

3

ビュー.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 %}
于 2013-03-03T13:46:06.723 に答える
0

これがあなたが求めているものであるかどうかは100%わかりませんが、ユーザーにGENRES_CHOICEのリストを表示したい場合は、テンプレートでこれを行うことができます。

{% for choice_id, choice_label in genres %}
           <p> {{ choice_id }} - {{ choice_label }}   </p>        
{% endfor %} 

もちろん、ジャンルとしてGENRES_CHOICEを渡します

于 2013-03-04T09:43:04.893 に答える
0

テンプレートで get_modelfield_display() メソッドを使用できます。

{{ book.get_genre_display }}
于 2013-12-14T13:09:10.720 に答える