Search code examples
pythondjangodjango-admindjango-apps

How to get current app when user is in Django admin?


I need to get from which admin page(app) current request is from in django admin.

Currently request.resolver_match.app_name only returns "admin" which is not what I want. I have noticed that my app name is in 'view_name' and 'url_name' but is it reliable to parse these variables to access current app name? Django 1.11 LTS

EDIT: For example, when a user enters admin page for my course app with the above method I still only get 'admin' in my request which should be 'course' not 'admin'. My ultimate goal is to hide some of my app model fields in admin page based on user group.

Thanks


Solution

  • From a ModelAdmin you have access to the model via self.model. In a ModelAdmin method you can thus get the app name using self.model._meta.app_label.

    I you need to access it from the template rather than the ModelAdmin, self.model._meta is passed to the context as opts. You can thus access it via {% if opts.app_label == "some_app" %}.