【发布时间】:2015-04-29 14:53:48
【问题描述】:
它涉及通用视图,特别是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 模型?我从来没有声明过,而且型号名称以大写字母开头。
教程说,“对于 DetailView,问题变量是自动提供的——因为我们使用的是 Django 模型(问题),所以 Django 能够确定上下文变量的适当名称。”
它是如何做到的?如果我进入并将变量大写,它就不再起作用了。 DetailView 是从哪里得到这个变量的?
【问题讨论】:
标签: django django-templates django-views django-generic-views