views:

89

answers:

3

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 .

Thanks in anticipation.

+3  A: 

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

Ignacio Vazquez-Abrams
Does Django store the name of the currently logged in user in some attribute, So that i could grant access to my pages based on that (I am new to django)
Peter Anderson
The user is stored in `request.user`. From there it's just a matter of accessing the attributes on the `User` model.
Ignacio Vazquez-Abrams
that is what I was looking for !! thanks a lot .
Peter Anderson
+4  A: 

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.

race1
Great one. It worked . Thanks a lot ! U rock!!
Peter Anderson
A: 

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/

Mark Lavin