2016-08-31 2 views
2

、テンプレートdetails.htmlは、我々が返されないかviews.pyDetailsViewクラス内の任意のcontext_object_nameを定義したことがないが、albumviews.pyによってそれに渡されたことを知っているんどのように。 さまざまなものがここでどのように結びついているか説明してください。Djangoジェネリックビュー:DetailViewは自動的にテンプレートに変数を提供しますか?次のコードで

details.html

{% extends 'music/base.html' %} 
{% block title %}AlbumDetails{% endblock %} 

{% block body %} 
    <img src="{{ album.album_logo }}" style="width: 250px;"> 
    <h1>{{ album.album_title }}</h1> 
    <h3>{{ album.artist }}</h3> 

    {% for song in album.song_set.all %} 
     {{ song.song_title }} 
     {% if song.is_favourite %} 
      <img src="http://i.imgur.com/b9b13Rd.png" /> 
     {% endif %} 
     <br> 
    {% endfor %} 
{% endblock %} 

views.py

from django.views import generic 
from .models import Album 

class IndexView(generic.ListView): 
    template_name = 'music/index.html' 
    context_object_name = 'album_list' 

    def get_queryset(self): 
     return Album.objects.all() 

class DetailsView(generic.DetailView): 
    model = Album 
    template_name = 'music/details.html' 

urls.py

from django.conf.urls import url 
from . import views 

app_name = 'music' 

urlpatterns = [ 

    # /music/ 
    url(r'^$', views.IndexView.as_view(), name='index'), 

    # /music/album_id/ 
    url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='details'), 

] 

事前に感謝します!

答えて

3

あなたがget_context_name()の実装を確認する場合は、この表示されます:あなたはget_context_data()がに追加されますことがわかります

def get_context_data(self, **kwargs): 
    """ 
    Insert the single object into the context dict. 
    """ 
    context = {} 
    if self.object: 
     context['object'] = self.object 
     context_object_name = self.get_context_object_name(self.object) 
     if context_object_name: 
      context[context_object_name] = self.object 
    context.update(kwargs) 
    return super(SingleObjectMixin, self).get_context_data(**context) 

def get_context_object_name(self, obj): 
    """ 
    Get the name to use for the object. 
    """ 
    if self.context_object_name: 
     return self.context_object_name 
    elif isinstance(obj, models.Model): 
     return obj._meta.model_name 
    else: 
     return None 

そして(SingleObjectMixinから)get_context_data()の実装をその辞書はcontext_object_nameget_context_object_name())のキーを持つエントリで、self.context_object_nameが定義されていない場合はobj._meta.model_nameを返します。この場合、get_object()を呼び出すget()への呼び出しの結果、ビューはself.objectになりました。 get_object()は、定義したモデルを取り、urls.pyファイルで定義したpkを使用してデータベースから自動的にクエリを実行します。

http://ccbv.co.uk/は、Djangoのクラスベースのビューが単一のページで提供しなければならないすべての機能と属性を見るための非常に良いウェブサイトです。

+0

これは、 'details.html'に' album'の代わりに他の変数名を使用した場合、動作しないため、context_object_nameを明示的に使用して変数を定義する必要があることを意味します。 – lordzuko

+0

'get_context_name()'がいつ呼び出されるのか教えてください。 – lordzuko

+1

@ lordzuko、あなたの最初のコメントにはい:変数の名前はあなたのモデル名によって決まります。明示的に定義することができます。 'get_context_name()'は、ビューがGETリクエストを受け取るたびに呼び出されるget()メソッドで呼び出されます。 –

関連する問題