Django:使用管理员上下文扩展基于类的视图的上下文 [英] Django: Extend context of class based view with Admin context
问题描述
我有一个基于类的视图,只显示配置列表。
I have a class based view which just displays a list of configurations.
使用以下代码将此视图添加到Django Admin站点:
This view is added to the Django Admin site by using the following code:
@admin.register(ZbxHostConf)
class ZbxHostConfListViewAdmin(admin.ModelAdmin):
review_template = 'admin/admzbxhostconf_list.html'
def get_urls(self):
urls = super(ZbxHostConfListViewAdmin, self).get_urls()
my_urls = patterns('',
(r'^zbxhostconflist/$', self.admin_site.admin_view(self.review)),
)
return my_urls + urls
def review(self, request):
return ZbxHostConfListView.as_view()(request)
模板扩展了 admin / base_site.html
模板。只有登录Django Admin站点后,我才能访问该站点。不幸的是,模板无法访问管理视图提供的上下文数据。
The template extends the admin/base_site.html
template. I can access the site only after I log in to the Django Admin site. Unfortunately the template cannot access the context data provided by the admin view.
由于Django文档建议将直接向 TemplateResponse提供上下文数据
function:
As the Django documentation suggests the context data will be provided directly to the TemplateResponse
function:
def my_view(self, request):
# ...
context = dict(
# Include common variables for rendering the admin template.
self.admin_site.each_context(request),
# Anything else you want in the context...
key=value,
)
return TemplateResponse(request, "sometemplate.html", context)
对于基于函数的视图,可以使用extra_context参数,但基于类的视图不提供此参数。我想我必须修改get_context_data函数,但我不太明白我可以如何将管理上下文数据提供给我的基于类的视图的get_context_data函数。任何建议?
For function-based views there is the possibility of the extra_context argument but class-based views don't provide this argument. I guess I have to modify the get_context_data function but I don't really understand how I can provide the admin context data to the get_context_data function of my class based view. Any suggestions?
推荐答案
这可能不是正确的答案,但我相信你可以尝试这样的事情。
This might not be a correct answer, but I believed you could try something like this.
#!/usr/bin/python3
from django.contrib import admin
class MyTemplateView(TemplateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update(admin.site.each_context(self.request))
return context
这篇关于Django:使用管理员上下文扩展基于类的视图的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!