Django Generic Views:DetailView如何自动为模板提供变量?

时间:2016-08-31 00:10:33

标签: python django django-generic-views

在以下代码中,模板details.html如何知道albumviews.py传递给context_object_name,尽管我们从未在{{{}}中返回或定义任何DetailsView 1}} views.py中的类。 请解释一下这里的各种事情是如何联系起来的。

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

]

提前致谢!!

2 个答案:

答案 0 :(得分: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()),当obj._meta.model_name isn&#时返回self.context_object_name的条目39; t定义。在这种情况下,由于调用self.object调用get(),视图得到get_object()get_object()使用您已定义的模型,并使用您在pk文件中定义的urls.py自动从数据库中查询该模型。

http://ccbv.co.uk/是一个非常好的网站,用于查看Django基于类的视图在一个页面中提供的所有函数和属性。

答案 1 :(得分:0)

如果未设置context_object_name,则上下文名称将由查询集所组成的模型的model_name构造而成,

https://docs.djangoproject.com/en/3.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_object_name