Django - Showing different templates to admins
Asked Answered
C

3

8

In Django what's the best way to implement templates with extra functionality for users with 'admin' permissions.

I'm not sure if I should create a set of completely different views specific for admins or integrate it into my existing views and templates like 'if user is an admin' everywhere.

Is there a standard way to do this in Django?

Custom answered 25/2, 2012 at 20:29 Comment(0)
D
10

This will show the stuff only if you are active and staff not admin:

{% if request.user.is_active and request.user.is_staff %}
    {% include "foo/bar.html" %}
{% endif %}

If you wanna show only and ONLY for admin you have to do that:

{% if request.user.is_superuser %}
    ADD your admin stuff there.
{% endif %}

Differences about these fields here.

Directorate answered 22/8, 2013 at 14:3 Comment(0)
J
3

If you have the the user available in template context you can do:

{% if user.is_active and user.is_staff %}
    Only the admin will see this code. For example include some admin template here:
   {% include "foo/bar.html" %}
{% endif %}

User will be available in your template f you use RequestContext and your TEMPLATE_CONTEXT_PROCESSORS setting contains django.contrib.auth.context_processors.auth, which is default. See authentication data in templates as reference.

Jacintha answered 26/2, 2012 at 10:46 Comment(0)
S
2

I'm an advocate of keeping as much logic out of the view layer (speaking generally about the MVC Design Pattern). So why not use decorators to direct your user to different views based upon their privilege? In your urls.py, define a pattern for admins:

url(r'^admin/$', 'user.views.admin_index'),
#do so for your other admin views, maybe more elegantly than this quick example

Then define a decorator to kick the user out if they're not an admin

def redirect_if_not_admin(fn):
def wrapper(request):
    if request.user.is_staff():
        return fn(request)
    #or user.is_superuser(), etc
    else:
        return HttpResponseRedirect('/Permission_Denied/')
return wrapper

And in your admin views

@redirect_if_not_admin
def index(request):
##do your thing 

It's more code than the other two answers, which are not wrong. It's just a personal preference to keep clutter down in the views.

Schuh answered 26/12, 2013 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.