I have a view defined for a url \'site/main/\'. I would like to be able to have (unauthenticated) users redirected to the default \'/admin/\' page for login, then redirected to
If you want to redirect to admin for login for specific view, and then to redirect back to the view url after successful login you only need to do two things:
- Add
LOGIN_URLtosettings.pyinside yourdjango project module:
...
LOGIN_URL = '/admin/login/'
- Add
@login_requiredas decorator to your view function insideviews.py:
from django.contrib.auth.decorators import login_required
...
@login_required
def main(request):
Once you set
LOGIN_URL = '/admin/login/'you can use@login_requiredon whateverviewin entire django project and itwill redirect to admin for loginandafter successful login will redirect backto the view url.Also now you don't need to use
is_authenticatedany more inside of a view as Daniel Roseman already said.The good thing is that now you also don't need to build a login template and wire it up to the built-in login views.
What is also good with this approach is the you have flexibility to easily add or remove this kind of authentication to whatever view you want.