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.
urls.py:
url('^', include('django.contrib.auth.urls')),
registration/login.html:
<h3>Login foo</h3>
<form method="post" action="">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
views.py
def only_for_users(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/?next=%s' % request.path)
// fetch some really interesting data
env=(django.get_version(),settings.BASE_DIR,sys.version) envMod=collections.OrderedDict(sorted(sys.modules.items())) return render(request,'env.html',{'env':env, 'envMod':envMod})
It works for Django 1.6 and uses the built-in login (look at the urls.py) and template. So you do not need to build a view function.
Info on urls
Your request.path shouldn't be /main/. Try it without the first.
You're missing an initial / in the URL: /admin/?next=...
However this still won't work, as the admin URL doesn't know anything about the next parameter. That's only for the actual login views. With your code, the user will be logged into the admin but will not be redirected back to your page.
You should build a login template and wire it up to the built-in login views. Then instead of checking is_authenticated in the view, you should just use the login_required decorator.
@login_required
def main(request):
...