學習《Django By Example》的錯誤及解決方法(個人學習記錄)
使用的環境:pycharm2018.1+Django2.1
第一章:
1.錯誤:author = models.ForeignKey(User, related_name='blog_posts')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
解決方案:author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE)
錯誤原因:指定外來鍵的方式不對。
2.錯誤:blogf.Post: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one
field).
解決方案:將ordering的型別改為元組。
3.建立超級使用者時,密碼不能少於8位。不能過於簡單。
4.get_object_or_404 方法需要引用
from django.shortcuts import get_object_or_404
5.ModuleNotFoundError: No module named 'django.core.urlresolvers'
錯誤原因:django2.0 把原來的 django.core.urlresolvers 包 更改為了 django.urls包,所以我們需要把匯入的包都修改一下就可以了。
6.錯誤:
url(r'^blogf/', include('blogf.urls', namespace='blogf',app_name='blogf),
解決方案:參考https://www.cnblogs.com/wendaobiancheng/p/9109257.html
可寫為:
url(r'^blogf/', include(('blogf.urls', 'blogf'), namespace='blogf')),
7.錯誤:不匹配錯誤:
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
解決方案: 在 django中推薦使用的是path,後改為了
path('<int:year>/<int:month>/<int:day>/<slug>/',
views.post_detail, name='post_detail'),
這樣改完後,出現了一個無法解析的錯誤,原因出在時間解析上,最簡單的方法是刪除get_absolute()中時間的引數,去檢視中也做相應修改。又或者是對時間引數進行重寫。
8:django.urls.exceptions.NoReverseMatch: Reverse for ' post_detail' not found. ' post_detail' is not
a valid view function or pattern name.
解決方法:發現自己沒有寫錯,通過查詢發現
return reverse('blog:post_detail', args=[self.slug])
冒號後不能有空格
本人第一次寫,如有不正確的地方,歡迎指正。