2016-08-31 63 views
2

在以下代碼中,模板details.html如何知道album已由views.py傳遞給它,但我們從未返回或定義過類中的任何context_object_nameviews.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()實現,你會看到這一點:

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 

併爲get_context_data()實施工作(SingleObjectMixin):

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) 

所以你可以看到,get_context_data()增加字典中輸入密鑰context_object_name(來自get_context_object_name()),當self.context_object_name未定義時,它將返回obj._meta.model_name。在這種情況下,由於致電get()調用get_object(),視圖得到self.objectget_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請求就會調用它。 –

相關問題