Cannot find reference ‘url’ in ‘init.py’

遇到的问题

from django.conf.urls import url 不能使用,无法使用

Cannot find reference ‘url’ in ‘init.py’


问题描述

使用url(‘admin/’, admin.site.urls)报错


原因分析:

url 已在Django 4.0中删除。请查看此处的发行说明:

https://docs.djangoproject.com/pl/4.0/releases/4.0/#features-removed-in-4-0

django.conf.urls.url() is removed.


解决方案:

使用 re_path 替代 url
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'),
]

使用re_path可以直接将以前的ur()换成re_path()就可以使用

使用path
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.
Cannot find reference ‘url’ in ‘init.py’_第1张图片

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

如果呢有一个需要更新许多URL模式的大型项目,你可能会发现django升级库对更新url.py文件很有用。

你可能感兴趣的:(bug,django,python,后端)