Skip to content

Instantly share code, notes, and snippets.

@m4rc1e
Created June 27, 2016 08:56
Show Gist options
  • Save m4rc1e/b28cfc9d24c3c2c47f21f2b89cffda86 to your computer and use it in GitHub Desktop.
Save m4rc1e/b28cfc9d24c3c2c47f21f2b89cffda86 to your computer and use it in GitHub Desktop.
Django decorator for views that allow only unauthenticated users to access view.
from django.shortcuts import redirect
def anonymous_required(redirect_url):
"""
Decorator for views that allow only unauthenticated users to access view.
Usage:
@anonymous_required(redirect_url='company_info')
def homepage(request):
return render(request, 'homepage.html')
"""
def _wrapped(view_func, *args, **kwargs):
def check_anonymous(request, *args, **kwargs):
view = view_func(request, *args, **kwargs)
if request.user.is_authenticated():
return redirect(redirect_url)
return view
return check_anonymous
return _wrapped
@gtsakoumakis2004
Copy link

is_authenticated has been changed to an attribute, parentheses after it are now a syntax error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment