django: Require login on view

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:

if isinstance(request.user, AnonymousUser):
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:

LOGIN_URL = '/user/login/'

And then in your view:

from django.contrib.auth.decorators import login_required

@login_required
def some_protected_view(request):
# code goes here

That's it!

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