Django通用视图:在本教程中,DetailView如何自动提供变量?

Django通用视图:在本教程中,DetailView如何自动提供变量?,django,django-templates,django-views,django-generic-views,Django,Django Templates,Django Views,Django Generic Views,它涉及一般视图,特别是DetailView及其在Django教程第4部分中的解释 我的URL如下所示: 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.Detail

它涉及一般视图,特别是
DetailView
及其在Django教程第4部分中的解释

我的URL如下所示:

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
这都是教程中的内容。顺便说一句,让我们看看my 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}
{%if error\u message%}{{{error\u message}{%endif%}
{%csrf_令牌%}
{问题中的选项为%choice\u set.all%}
{{choice.choice_text}}
{%endfor%}
我的详细信息模板如何知道问题变量(如,
question.question_text
)引用我的
question
模型?我从未声明过,型号名称以大写字母开头

教程说,“对于DetailView,问题变量是自动提供的——因为我们使用的是Django模型(问题),Django能够为上下文变量确定一个合适的名称。”


它是怎么做到的?如果我把变量大写,它就不起作用了。
DetailView
从何处获取此变量?

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

>>> Question._meta.model_name
'question'
问题==对象 基本上,为模型问题设置的内容类型是问题。在应用程序名称和模型名称中指定的模型上执行完整内容类型查找(即..问题\问题)


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

如何确定此模型名称?是的,它是一个小写的
\u meta.object\u name
模型类的名称。谢谢!这回答了我的问题。