15

I have configured my python env with python 3.5, but I am getting the following error when I run my server with the command python manage.py runserver

from django.contrib.auth.views import logout
ImportError: cannot import name 'logout'

this is my config

dj-database-url==0.5.0
Django==2.1a.1
gunicorn==19.8.1
numpy==1.14.3
psycopg2==2.7.4
pytz==2018.4
whitenoise==4.0b4

I tried reinstalling my env and changing python version but issue stills happening.

Thanks for your questions guys

MenoTx
  • 153
  • 1
  • 1
  • 4
  • 1
    Since django-1.11, the login, logout, etc. function-based views have been rewritten to (class-based views)[https://stackoverflow.com/a/51906537/2351696] – suhailvs Mar 27 '19 at 08:49

7 Answers7

27
ImportError: cannot import name 'login' from 'django.contrib.auth.views'

I had this error and looked up for a solution found it here. Remove views from import

Works for me in Python 3.7 and Django 2.2. No need to downgrade to Django 2.0.4(as LTS is in 2.2)

It was this one that caused me the error.

from django.contrib.auth.views import login

Had to change it to

from django.contrib.auth import login

Worked for logout too.

Venkatesh Gotimukul
  • 741
  • 1
  • 9
  • 30
4

Hey looks like you are using the wrong django version, django.contrib.auth.views.logout is not available in your current django version, try downgrading your django version to a lower version with this command: sudo pip install Django==2.0.2 or change the import in order to use logout_view

Juanse
  • 1,194
  • 10
  • 16
3

settings.py

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

urls.py

from django.conf.urls import url
from django.contrib.auth.views import LogoutView

urlpatterns = [
    url(r'^logout$', LogoutView.as_view(), name='logout'),
]

it's work for me on django 3.0.x

2

this is for django 2.x, docs

from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
0

This is the code I added to urls.py to get login working:

def my_logout(request):
    logout(request)
    return redirect('index')

along with urlpatterns:

path('logout/', my_logout, name="logout"),

Works for me in Python 2.7, Django 2.1.5!

jxmorris12
  • 1,262
  • 4
  • 15
  • 27
0

In the latest version of Django (django == 3.2.4) the import should be the following

from django.contrb.auth.views import LogoutView

-1

Pyhton is very case sensitive... make sure your code lines up with proper whitespace. I go this error and make functions created in views.py were not aligned

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 30 '23 at 06:32