Django: detect admin login in view or template

In templates:

{% if user.is_superuser %}
    <p>Hello, admin.</p>
{% else %}
    <p>Hello, ordinary visitor.</p>
{% endif %}

In views:

if request.user.is_superuser:
    # Hello, admin.
else:
    # Hello, ordinary visitor.

Depending on your needs, is_staff might be a better fit than is_superuser. You can read about the difference here.


Joseph's answer is fine for your simple case, but in reality neither is_staff nor is_superuser is a perfect fit. Assuming your page is, say, /polls/ (a list of Poll objects, in an app called poll), you should test the specific poll.change_poll and poll.delete_poll permissions.

In a template:

{% for poll in polls %}
    {% if perms.poll.change_poll %}<a href='/polls/edit/{{ poll.id }}'>Edit</a>{% endif %}
    {% if perms.poll.delete_poll %}<a href='/polls/delete/{{ poll.id }}'>Delete</a>{% endif %}
{% endfor %}

Or in a view using has_perm:

if not request.user.has_perm('poll.change_poll'):
    return HttpResponseForbidden('Nope!')

Or in a view using a decorator:

@permission_required('poll.change_poll')
def edit_poll(request, poll_id):
    # ....

You can assign these permissions directly to a user, to a group (and then put a user in that group) or by setting is_superuser.


If you don't care about the privileges a user has and just want to make sure they are logged in, you can use user.is_anonymous, which will be true if the user is logged out and false if they are logged in.

By default, user.is_staff is required for the user to have access to the Django Admin.