Philipp Wiesner
Philipp Wiesner

Reputation: 167

Django: Extend context of class based view with Admin context

I have a class based view which just displays a list of configurations.

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)

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.

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)

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?

Upvotes: 5

Views: 3241

Answers (1)

Yeo
Yeo

Reputation: 11784

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

Upvotes: 9

Related Questions