【问题标题】:Django Generic Views: In the tutorial, how does DetailView automatically provide the variable?Django Generic Views:教程中,DetailView如何自动提供变量?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      >>> Question._meta.model_name
      'question'
      

      【讨论】:

      • 这个型号名称是如何确定的?是否只取整个模型的名称并将其变为小写?
      • 是的,它是一个小写的_meta.object_name,它是模型类的名称。
      • 谢谢!这回答了我的问题。
      猜你喜欢
      • 1970-01-01
      • 2019-02-12
      • 2019-10-02
      • 2011-08-11
      • 2017-01-22
      • 2021-12-04
      • 2021-05-03
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多