django: Require login on view

0 Comments

There's a real easy way of doing this in Django.

Sure you can manually write a check on every single view that requires a login to see if the user is an AnonymousUser:

1.if isinstance(request.user, AnonymousUser):
2.  return HttpResponseRedirect(reverse('do-login'))

or you can just use a decorator and set the LOGIN_URL via the settings.

In your settings file, add:

1.LOGIN_URL = '/user/login/'

And then in your view:

1.from django.contrib.auth.decorators import login_required
2. 
3.@login_required
4.def some_protected_view(request):
5.  # code goes here

That's it!

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog