I'm using django.contrib.auth
to handle user authentication in my django project. In order to log in, I have
from django.contrib.auth.views import login, logout
# ...
url(r'^login/', login, name='login'),
url(r'^logout/', logout, {'next_page': '/'}, name='logout'),
in my main project's urls.py
.
So far, so good. However, I notice that after logging in, if I access /login/
, I still see the login page, and am able to log in as another user. This seems like counter-intuitive behavior -- most websites will either show an error or redirect you to the homepage if you attempt to access the login page while logged in.
I'm using the builtin models / views, and so as far as I know I have no easy way of altering the views. Is there a simple way of gaining this functionality (i.e. preventing access to the login form if logged in), or is the best way simply to modify the template to only show the form if not logged in?
Simply you can write you login url as this:
from django.contrib.auth import views as auth_views
path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html", redirect_authenticated_user=True), name='login'),
You hide content within the template.html
using templateTags
like so:
{% if user.is_authenticated %}
<p>Only a logged in User can view</p>
{% else %}
<p>Only a logged out User can view</p>
{% endif %}
[EDIT]
If you would like to then redirect the user before the web page is rendered, then you can do that in the view.
def myView(request):
if request.user.is_authenticated:
return render(request, 'logged_in_view.html')
else:
return render(request, 'logged_out_view.html')
Possible solution: I create 'my_login':
def my_login(request):
if request.user.is_authenticated():
return redirect(#...home)
else:
return login(request, 'template/login.html') # here i used login built-in function
# instead of using directly in urls.py
And i used my_login
view in urls.py instead of 'django.contrib.auth.views.login'
EDIT
New in Django 1.10:
The redirect_authenticated_user parameter was added.
Check https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.views.login
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With