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?
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With