[Solved]-Find out the currently logged in user in Django

17👍

Current user is in request object:

def my_view(request):
    current_user = request.user

It’s django.contrib.auth.models.User class and it has some fields, e.g.

  • is_staff – Boolean. Designates whether this user can access the admin site;
  • is_superuser – Boolean. Designates that this user has all permissions without explicitly assigning them.

http://docs.djangoproject.com/en/1.1/topics/auth/#django.contrib.auth.models.User

So to test whether current user is superuser you can:

if user.is_active and user.is_superuser:
    ...

You can use it in template or pass this to template as variable via context.

3👍

Sounds like you should be using the built-in permissions system for this.

0👍

Check out the user_passes_test decorator for your views. Django snippets has a related decorator:

These decorators are based on
user_passes_test and
permission_required, but when a user
is logged in and fails the test, it
will render a 403 error instead of
redirecting to login – only anonymous
users will be asked to login.

http://www.djangosnippets.org/snippets/254/

Leave a comment