2016-01-29 26 views
2

想不通爲什麼錯誤NoReverseMatch, 試圖在頁面上顯示的Home.htmlNoReverseMatch在/博客/ Django1.9 URL

查看鏈接:

def show_article(request, article_id): 
    article = get_object_or_404(Article, id=article_id) 
    return render(request, 'blog/article.html', {'article': article}) 

網址:

urlpatterns = [ 
    url(r'^$', views.home, name="home"), 
    url(r'^about/$', views.about, name='about'), 
    url(r'^contact/$', views.contact, name='contact'), 
    url(r'^article/(?P<article_id>[0-9]+)/$', views.show_article, name='article'), 
] 

的Home.html:

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

{% block contaner %} 
<div class="NameT">Главная</div> 
<p> 
    {% for article in articles %} 
    <h4><a href="{% url 'article' article_id %}">{{ article.title }}</a></h4> 
    <div><pre>{{ article.get_short_text }}</pre></div> 
    {% endfor %} 
</p> 
{% endblock %} 

article.html:

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

{% block contaner %} 
    <h1>{{ article.title }}</h1> 
    <pre>{{ article.text }}</pre> 
{% endblock %} 

例外:

Exception Type: NoReverseMatch 

Exception Value:  

Reverse for 'article' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/article/(?P<article_id>[0-9]+)/$'] 

回答

4

<h4><a href="{% url 'article' article_id %}">{{ article.title }}</a></h4>是錯誤的,它應該是:

<h4><a href="{% url 'article' article.id %}">{{ article.title }}</a></h4>

您通過article_id作爲參數,但該變量不存在。但article.id是一篇文章的ID,它是一個有效的值,並且很可能是您需要的。