Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logged in users still see login page (django auth)

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?

like image 661
Mala Avatar asked Apr 08 '14 19:04

Mala


3 Answers

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'),
like image 179
Ahmed Ibrahim Avatar answered Oct 06 '22 00:10

Ahmed Ibrahim


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')
like image 23
Aaron Lelevier Avatar answered Oct 05 '22 23:10

Aaron Lelevier


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

like image 30
yierstem Avatar answered Oct 06 '22 00:10

yierstem