Django Generic Views:教程中DetailView是如何自动提供变量的?

Django Generic Views: In the tutorial, how does DetailView automatically provide the variable?

它涉及通用视图,特别是 DetailView 并且在 Django 教程第 4 部分中有解释。

我的网址如下所示:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),)

我的观点是这样的:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic

from polls.models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

def get_queryset(self):
    """Return the last five published questions."""
    return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above

顺便说一句,这全部来自教程。让我们看看我的 detail.html 模板:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

我的详细信息模板如何知道问题变量(如 question.question_text)指的是我的 Question 模型?我从来没有声明过,型号名称以大写字母开头。

教程说,"For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable."

它是怎么做到的?如果我进去并将变量大写,它就不再起作用了。 DetailView 从哪里获取这个变量?

此数据在模型的元信息中可用。您也可以在代码中获取它:

>>> Question._meta.model_name
'question'

问题==对象 基本上,为模型问题设置的内容类型是问题。对您从应用程序名称和模型名称指定的模型执行完整的内容类型查找(即 question__question)

这也适用于 Django 的通用关系,您可以在查找中指定模型名称,而不是首先获取内容类型。