[英]Find out the currently logged in user in Django
I have created a list of 5 users. 我创建了一个包含5个用户的列表。 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 它是django.contrib.auth.models.User类,它有一些字段,例如
http://docs.djangoproject.com/en/1.1/topics/auth/#django.contrib.auth.models.User 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. 查看用户视图的user_passes_test装饰器。 Django snippets has a related decorator:
Django片段有一个相关的装饰者:
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.
这些装饰器基于user_passes_test和permission_required,但是当用户登录并且测试失败时,它将呈现403错误而不是重定向到登录 - 只有匿名用户才会被要求登录。
http://www.djangosnippets.org/snippets/254/ http://www.djangosnippets.org/snippets/254/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.