简体   繁体   中英

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.

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, eg

  • 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.

听起来你应该使用内置的权限系统

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM