我已经开始学习django,我不确定通用视图是如何工作的 . 我多次阅读django文档,我无法清楚地了解泛型视图的工作原理 . 很奇怪,但效果很好 . 它从数据库中检索数据并在浏览器上呈现数据 .
这是 polls/urls.py 的片段代码 .
url(r'^$', views.IndexView.as_view(), name = 'index')
它将在 views.py 中转到 IndexView 类 .
这是 polls/views.py 的片段代码 .
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
当我将 template_name 更改为 something 时,异常发生如下 .
TemplateDoesNotExist:polls / question_list.html
question_list.html 是什么意思?
它从何而来?
这是 index.html .
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>
<a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
如您所见, index.html 文件使用 latest_question_list 作为参数,但我不确定如何使用 latest_question_list .
在 views.py 文件中, context_object_name = 'latest_question_list' 是什么意思?
'latest_question_list' 来自何处 index.html 如何使用 latest_question_list ?
我在 views.py 中使用 context_object_name 吗?
get_queryset() 功能的作用是什么?
2 回答
question_list.html是什么意思?
我在views.py中使用context_object_name吗?
get_queryset()函数的作用是什么?
我理解他们的意思 .
默认情况下, DetailView 泛型视图使用名为 /_detail.html. 的模板 . 在我的示例中,它将使用模板 "polls/question_detail.html" . template_name 属性用于告诉Django使用特定模板名称而不是自动生成的默认模板名称 . 我还为 results 列表视图指定了 template_name - 这确保了结果视图和细节视图在渲染时具有不同的外观,即使它们在幕后都是 DetailView .
对于 DetailView ,问题变量是自动提供的 - 因为我们使用的是Django模型( Question ),Django能够为上下文变量确定一个合适的名称 . 但是,对于 ListView ,自动生成的上下文变量为 question_list . 要覆盖它,我们提供 context_object_name 属性,指定我们要使用 latest_question_list .