Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the currently logged in user in Django

I have created a list of 5 users. How do I find out which user has logged in currently? Also please mention, if there is any way to find out if the super-user has logged in?

My requirement is, I want to restrict the access of certain pages in the templates only to the superuser.

like image 839
Peter Anderson Avatar asked Feb 07 '10 13:02

Peter Anderson


People also ask

How can I tell if a Django account is active?

If is_active is True (default), returns only active users, or if False , returns only inactive users. Use None to return all users irrespective of active state.

How do I find my Django username and password?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

What is Auth_user_model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.


1 Answers

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.

like image 79
demalexx Avatar answered Oct 16 '22 11:10

demalexx