平臺: Django 2.0.1 Python 3.6.3
之前學習Python的時候遇到過許多問題. 許多教程都是基于舊版本, 版本更新之后許多教程就不再適用了.
Django舊版本中設置url是這樣的:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'my_blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'article.views.home'),
)
由于Django 2.0版本發(fā)布以后, 生成的默認配置變成了這樣:
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
url不見了, 變成了path. 如果按照教程導入patterns, include, url模塊或者修改path為url就會導致各種報錯. 比如:
TypeError: view must be a callable or a list/tuple in the case of include().
NameError: name 'url' is not defined
NameError: name 'include' is not defined\
ImportError: cannot import name 'views'
通過搜索并查閱了版本更新文檔之后, 發(fā)現(xiàn)django.conf.urls.url()
方法變成了django.urls.re_path()
, django.conf.urls.include()
方法現(xiàn)在從django.urls
導入.
在實際項目中, 還需要導入views
, 即from xxx import views
, 把url方法改成path方法, 參考默認配置時生成的例子. 如下:
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.xxx),
]
這樣就可以正常的調(diào)用views里面的xxx方法了.
平臺: Django 2.0.1 Python 3.6.3