Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Staff Decorator

I'm trying to write a "staff only" decorator for Django, but I can't seem to get it to work:

def staff_only(error='Only staff may view this page.'):     def _dec(view_func):         def _view(request, *args, **kwargs):             u = request.user             if u.is_authenticated() and u.is_staff:                 return view_func(request, *args, **kwargs)             messages.error(request, error)             return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home')))         _view.__name__ = view_func.__name__         _view.__dict__ = view_func.__dict__         _view.__doc__ = view_func.__doc__         return _view     return _dec 

Trying to follow lead from here. I'm getting:

'WSGIRequest' object has no attribute '__name__'

But if I take those 3 lines out, I just get a useless "Internal Server Error". What am I doing wrong here?

like image 733
mpen Avatar asked Apr 22 '10 19:04

mpen


People also ask

Is staff permission in Django?

By default, all Django models are given add , change and delete permissions, which you can assign to staff users. As a consequence, each of these model permissions represents an access permission for a Django admin page.

What is Is_staff in Django?

Those flags are used in the Django Admin app, the is_staff flag designates if the user can log in the Django Admin pages. Now, what this user can or cannot do, is defined by the permissions framework (where you can add specific permissions to a given user, e.g. can create/update users but cannot delete users).

What are decorators in Django?

Decorators are a way to restrict access to views based on the request method or control caching behaviour. This is particularly useful when you want to separate logged-in users from unauthenticated users or create an admin page that only privileged users can access.


1 Answers

This decorator already exists as

from django.contrib.admin.views.decorators import staff_member_required  @staff_member_required 

Trunk: http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/views/decorators.py

like image 66
Mark Lavin Avatar answered Nov 04 '22 06:11

Mark Lavin