get_context_data可以用于给模板传递模型以外的内容或参数,非常有用。例如现在的时间并不属于Article模型。如果你想把现在的时间传递给模板,你还可以通过重写get_context_data方法(如下图所示)。因为调用了父类的方法, # Create your views here. from django.views.generic import
函数get_context_data TemplateResponseMixin 将内容渲染到模板中 template_name template_engine response_class content_type 函数render_to_response ListView MultipleObjectTemplateResponseMixin TemplateResponseMixin 获取模板名字 首先根据template_name 如果没找到 自己根据 应用的名字,关联模型的名字, _list.html...
django ListView context_object_name = 'posts'. The template default name is ListView 'object_list' from.modelsimportPost,Categoryfromdjango.views.generic.listimportListViewfromdjango.shortcutsimportget_object_or_404classPostCategory(ListView): model = Post template_name ='cat.html'context_object_name...
objects.filter(your condition) def get_context_data(self,**kwargs): context = super(Viewname,self).get_context_data(**kwargs) context['price_form']=PriceForm(self.request.GET or None) return context 使用get_queryset(),您可以定义一个将由get_context_data()在super()中实现的基本查询集。
from django.views.generic import ListView class UsersView(ListView): model = UserProfile template_name = 'talks/users_list.html' context_object_name = 'user_list' def get_context_data(self, **kwargs): # 重写get_context_data方法 # 很关键,必须把原方法的结果拿到 ...
class TestView(ListView): model = User context_object_name = 'user_all' 这时通过在模板中遍历'user_all'也可以获取并展示用户数据信息。 3.3 添加额外的上下文 项目中,除了要展示用户信息,还有可能需要展示其他的额外信息,比如我要在测试页面上展示所有组织架构信息,这个时候就可以使用get_context_data()方法来...
BaseListView重写了get方法,是ListView的主要流程,先用MultipleObjectMixin中的get_queryset()获取self.object_list,然后通过allow_empty判断数据为空时是否显示内容。最后用MultipleObjectMixin.get_context_data()获取context,返回self.render_to_response(context)。
from django.views.genericimportListViewclassUsersView(ListView):model=UserProfile template_name='talks/users_list.html'context_object_name='user_list'defget_context_data(self,**kwargs):# 重写get_context_data方法 # 很关键,必须把原方法的结果拿到 ...
context = Super(AboutView, self).get_context_data() context['phone'] = '021-8888888' return context 1. 2. 3. 4. 5. 6. ListView:列表视图 在网站开发中,经常会出现需要列出某个表中的一些数据作为列表展示出来。比如文章列表,图书列表等等。在Django中可以使用ListView来帮我们快速实现这种需求。示例...
答案是子类化 DetailView ,并提供你实现的 get_context_data 方法。默认的实现只是将正在显示的对象增加到模板,但你需要覆盖它来发送更多信息: from django.views.generic import DetailView from books.models import Book, Publisher class PublisherDetail(DetailView): model = Publisher def get_context_data(self, ...