Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0

After upgrading to Django 4.0, I get the following error when running python manage.py runserver

  ...
  File "/path/to/myproject/myproject/urls.py", line 16, in <module>
    from django.conf.urls import url
ImportError: cannot import name 'url' from 'django.conf.urls' (/path/to/my/venv/lib/python3.9/site-packages/django/conf/urls/__init__.py)

My urls.py is as follows:

from django.conf.urls

from myapp.views import home

urlpatterns = [
    url(r'^$', home, name="home"),
    url(r'^myapp/', include('myapp.urls'),
]
like image 770
Alasdair Avatar asked Dec 11 '21 22:12

Alasdair


2 Answers

django.conf.urls.url() was deprecated in Django 3.0, and is removed in Django 4.0+.

The easiest fix is to replace url() with re_path(). re_path uses regexes like url, so you only have to update the import and replace url with re_path.

from django.urls import include, re_path

from myapp.views import home

urlpatterns = [
    re_path(r'^$', home, name='home'),
    re_path(r'^myapp/', include('myapp.urls'),
]

Alternatively, you could switch to using path. path() does not use regexes, so you'll have to update your URL patterns if you switch to path.

from django.urls import include, path

from myapp.views import home

urlpatterns = [
    path('', home, name='home'),
    path('myapp/', include('myapp.urls'),
]

If you have a large project with many URL patterns to update, you may find the django-upgrade library useful to update your urls.py files.

like image 88
Alasdair Avatar answered Sep 17 '22 13:09

Alasdair


I think a quick fix to this problem is to do followings;

You can easily replace

from django.conf.urls import url

to this:

from django.urls import re_path as url

And keep the rest of code to be same as before. (Thanks @Alasdair)

like image 45
Hosein Basafa Avatar answered Sep 19 '22 13:09

Hosein Basafa