Django: Staff Decorator

mpen picture mpen · Apr 22, 2010 · Viewed 29.6k times · Source

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?

Answer

Mark Lavin picture Mark Lavin · Apr 22, 2010

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