[英]get_context_data method Django
# views.py
from django.views.generic import ListView
from books.models import Publisher
class PublisherList(ListView):
model = Publisher
context_object_name = 'my_favorite_publishers'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['number'] = random.randrange(1, 100)
return context
使用 super() 调用 get_context_data 返回什么?
什么类型的信息?
从 get_context_data 返回的上下文是否给定了 contexT_object_name 'my_favorite_publishers'?
.get_context_data(..)
方法 [Django-doc]返回一个字典,其中包含将传递给模板进行渲染的上下文。
默认情况下, ListView
[Django-doc]将使用以下键和值创建字典:
'view'
: 映射到这个视图的实例;'paginator'
: 分页器对象,如果你分页,否则None
;'page_obj'
: 分页时当前页面的页面对象,否则为None
;'is_paginated'
:如果你分页为True
,否则为False
;'object_list'
:由ListView
制作的(可选)分页查询集; 和context_object_name
:如果你指定了一个context_object_name
(或者你已经覆盖了get_context_object_name
并且它没有返回None
,它也会将它与(可选)分页查询集相关联。 class EmployeeDetailView(DetailView):
queryset=Employee.objects.all()
template_name='testapp/detail.html'
def get_context_data(self,**kwargs):
context=super().get_context_data(**kwargs)
return context
在上面的例子中,EmployeeDetailView 类正在寻找一个对象(DetailView 的默认上下文),这个对象是通过调用父类中存在的方法提供的,即 get_context_data 这个方法接受 kwargs 作为参数。
kwargs 是一个可变长度的参数列表。函数 get_context_data 返回包含对象的上下文,这个对象将被发送到 detail.html 文件,以显示当前对象持有的数据(渲染过程)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.