2017-08-03 57 views
0

我目前正在關注「示例中的Django」一書以及第1章:構建博客應用程序,當我嘗試訪問127.0.0.1時出現以下錯誤: 8000 /博客/爲什麼我在Django的/ blog /中獲得NoReverseMatch

NoReverseMatch在/博客/

反轉爲 'post_detail' 與參數 '(2017年, '08', '03', '新標題')' 和關鍵字參數「 {}' 未找到。 1模式 嘗試: ['blog /(?P \ d {4})/(?P \ d {2})/(?P \ d {2})/ ^(?P [ - \ W] +) /$']

這裏是我的模板/博客/ base.html文件文件

{% load staticfiles %} 

<!DOCTYPE html> 

<html> 
<head> 
    <title>{% block title %} {% endblock %}</title> 
    <link href="{% static "css/blog.css" %}" rel="stylesheet"> 
</head> 
<body> 
    <div id = "content"> 
    {% block content %} 
    {% endblock %} 
    </div> 

    <div id = "sidebar"> 
    <h2> My Blog</h2> 
     <p> This is my blog </p> 
    </div> 
</body> 
</html> 

和我的模板/博客/職位/ list.html文件

{% extends "blog/base.html" %} 

{% block title %}My Blog {% endblock %} 

{% block content %} 
    <h1> My Blog </h1> 
    {% for post in posts %} 
    <h2> 
     <a href="{{ post.get_absolute_url }}"> 
     {{ post.title }} 
     </a> 
    </h2> 
    <p class="date"> 
     Published {{ post.publish }} by {{ post.author }} 
    </p> 

    {{ post.body|truncatewords:30|linebreaks }} 
    {% endfor %} 
{% endblock %} 

我似乎無法找到問題所在,所以我很感謝您的幫助。

如果有幫助,我在Linux系統上使用django 1.8.6和Python 3.6.2與virtualenvwrapper。

+0

請出示您的views.py和urls.py與崗位模型的models.py –

+0

檢查這個問題.. https://stackoverflow.com/questions/15417455/django-1-5-noreversematch-在博客希望你得到答案 –

回答

2

你的正則表達式中至少有兩個錯誤。

首先,你在最終模式之前有一個流浪^。這意味着「匹配從字符串的開頭」,因此將它放在字符串的中間將始終失敗。

其次,你在最後一個斜槓前有空格。

+0

謝謝!它現在有效。 –

0

嘗試通過原始代碼 blog/urls.py

from django.conf.urls import url 
from . import views 


urlpatterns = [ 
    # post views 
    #url(r'^$', views.post_list, name='post_list'), 
    url(r'^$', views.PostListView.as_view(), name='post_list'), 
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', 
     views.post_detail, 
     name='post_detail'), 
] 
0

更換您的博客urls.py你所缺少的是「post_detail」反向鏈接。您需要有一個名稱爲「post_detail」的url。

添加這的urls.py

url(r'^blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/^(?P[-\w]+) /$'', views.post_detail, name='post_detail'), 

您的觀點也應該接受正規表達式等;

def post_detail(request, pattern): 
    .... 
    return render(request, template, context)