0

How to pass extra context to listview or changeview ?

In this tutorial, we will see how it is easy to add extra context variables to change_list or change_form in Django Admin.

Within our class Shop in the admin

class ShopAdmin(admin.ModelAdmin):
    inlines = [shopplanning_inline]
    fieldsets = [
        (None, {'fields': ['user','name','email','address']}),
    ]
    list_display = ('user','name', 'email',  )
    ordering = ('user',)

We can override the default Django methods used to display listview page or changeview page which are:

def changelist_view(self, request, extra_context=None)

def change_view(self, request, object_id, form_url='', extra_context=None):

So to add a variable named myvar and pass it to the change_list or change_form templates, we just have to write:

    def changelist_view(self, request, extra_context=None):
        response = super(ShopAdmin, self).changelist_view(request, extra_context)
        extra_context = {
            'myvar': 'whateveryouwant'
        }
        try:
            response.context_data.update(extra_context)
        except Exception as e:
            pass
        return response

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra = extra_context or {}
        extra["nomCommerce"] = 'whateveryouwant'
        return super(ShopAdmin, self).change_view(request, object_id,
                     form_url, extra_context=extra)

And voila. Now you will be able to access your myvar variable in the Django admin change_list or change_form templates (if you have override it of course).

Christophe Surbier

Leave a Reply

Your email address will not be published. Required fields are marked *