4

I am currently working on a project in Django... I am trying to import login from django.contrib.auth.views but I get the following error:

ImportError: cannot import name 'login'

Here is my urls.py:

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

urlpatterns = [
    url('', views.home),
    url('login', login, {'template_name': 'accounts/login.html'})
]

error message(cmd):

ImportError: cannot import name 'login'
Alasdair
  • 298,606
  • 55
  • 578
  • 516

1 Answers1

8

The old function-based authentication views, including login, were removed in Django 2.1. In Django 1.11+ you should switch to the new class-based authentication views, including LoginView.

I suggest you also switch to use the new path() instead of url().

from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('', views.home),
    path('login', auth_views.LoginView.as_view(template_name='accounts/login.html')),
]

If you want to stick with url() or re_path(), then make sure you use ^ and $ to begin and end your regexes:

url(r'^$', views.home),
url(r'^login$', auth_views.LoginView.as_view(template_name='accounts/login.html')))
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Thank you so much that worked. I didn't put the (r'^) because I didn't think I needed it in Django 2, but will be using it from now on. Thanks for the code.(Apologies for the following question I accidentally submitted the comment when I was working it out lol). Thanks again! –  Sep 10 '18 at 13:49
  • In Django 2.0+, the simplest approach is to switch to `path()` then you don't need `^$`. You still need them with `url()`, since it behaves the same as in earlier versions of Django and still uses regexes. – Alasdair Sep 10 '18 at 13:52
  • @JShen if this answer helped you, don't forget to mark it as "accepted answer" – Antwane Sep 10 '18 at 14:32