You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decorators.py 1.4KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import urlparse
  2. from functools import wraps
  3. from django.contrib.auth import REDIRECT_FIELD_NAME
  4. from django.contrib import messages
  5. from django.utils.translation import ugettext_lazy as _
  6. def staff_member_required(view_func, login_url='/accounts/login/'):
  7. """
  8. Decorator for views that checks that the user is logged in and is a staff
  9. member. The user is redirected to the login page specified by *login_url*
  10. if not authenticated.
  11. This decorator is based on the admin decorator provided by the the django
  12. ``auth`` and ``admin`` packages.
  13. """
  14. @wraps(view_func)
  15. def _checklogin(request, *args, **kwargs):
  16. if request.user.is_active and request.user.is_staff:
  17. return view_func(request, *args, **kwargs)
  18. # If the login url is the same scheme and net location then just
  19. # use the path as the "next" url.
  20. path = request.build_absolute_uri()
  21. login_scheme, login_netloc = urlparse.urlparse(login_url)[:2]
  22. current_scheme, current_netloc = urlparse.urlparse(path)[:2]
  23. if ((not login_scheme or login_scheme == current_scheme) and
  24. (not login_netloc or login_netloc == current_netloc)):
  25. path = request.get_full_path()
  26. messages.warning(request, _("You must log in to access this page"))
  27. from django.contrib.auth.views import redirect_to_login
  28. return redirect_to_login(path, login_url, REDIRECT_FIELD_NAME)
  29. return _checklogin