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'), 

] 

미리 감사드립니다! 당신이 get_context_name()의 구현을 선택하면

답변

3

,이 나타납니다 :

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()의 구현 :

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()가 추가하는 사전 (get_context_object_name()에서) 가 정의되지 않은 경우 obj._meta.model_name을 반환하는 항목이 포함 된 사전입니다. 이 경우 get_object()을 호출하는 get()에 대한 호출의 결과로보기에 self.object이 표시됩니다. get_object()은 정의한 모델을 가져와 urls.py 파일에 정의한 pk을 사용하여 데이터베이스에서 자동으로 쿼리합니다.

http://ccbv.co.uk/은 장고의 클래스 기반보기가 단일 페이지에서 제공해야하는 모든 기능과 속성을보기에 매우 좋은 웹 사이트입니다.

+0

즉,'details.html'에서'album' 대신 다른 변수 이름을 사용했다면 작동하지 않고 context_object_name을 사용하여 명시 적으로 변수를 정의해야합니다. – lordzuko

+0

또한'get_context_name()'이 언제 호출되는지 알려주실 수 있습니까? – lordzuko

+1

@ lordzuko, 첫 번째 의견에 yes :) 변수의 이름은 모델 이름에 의해 결정됩니다. 명시 적으로 정의 할 수 있습니다. 'get_context_name()'은 뷰가 GET 요청을받을 때마다 호출되는'get()'메소드에서 호출된다. –

관련 문제