感谢各位同行的无私分享,此文为整理记录。
原书中Django是1.8.4版本,新版有不少变化。
我用的是Djangon 3.0.7,python3.6.9。
1,18章2.4小节.定义模型的外键方法ForeignKey()问题
书中原码:
1 | topic = models.ForeignKey(Topic) |
应改为:
1 | topic = models.ForeignKey(Topic,on_delete=models.CASCADE) |
2,18章3.1小节.映射URL
原url()方法改为了path()方法
书中原码:
1 2 3 4 5 6 7 | from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] |
方法一改为:
1 2 3 4 5 6 7 | from django.urls import include, path from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls', namespace='learning_logs')), ] |
方法二:
虽然新版url默认不支持正则,但是导入re_path就可以用了。
例:
1 2 3 4 5 | from django.urls import path,re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^test-(\d+)-(\d+)/', views.test), ] |
3,19章1.1小节3.视图函数 new_topic()
1 | from django.core.urlresolvers import reverse |
应改为:
1 | from django.urls import reverse |
4,19章2.2节登录页面
目录 learning_log/users/ 中,新建的urls.py 文件
1 2 3 4 5 6 7 8 | from django.conf.urls import url from django.contrib.auth.views import login from . import views urlpatterns = [ #登录页面 url(r'^login/$', login, {'template_name': 'users/login.html'}, name='login'), ] |
应该为:(包含后面章节注销、注册部分,对照#登录页面部分修改就可以。LoginView记得导入)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from django.urls import path,include from django.contrib.auth.views import LoginView from django.contrib.auth import logout,login,authenticate from . import views app_name = 'users' LoginView.template_name = 'users/login.html' urlpatterns = [ #登录页面 path('login/',LoginView.as_view(),name='login'), #注销 path('logout/',views.logout_view,name='logout'), #注册 path('register/',views.register,name='register'), ] |
模块引进有部分多余,调试好再来修改。