在我的博客上,我試圖創建一個URL尋呼系統,我可以通過ID鏈接到上一個和下一個帖子Post模型。現在,每次我試圖去一個博客網頁,我得到這個錯誤:
NoReverseMatch at /blog/2
Reverse for 'blog_detail_url' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P<id>\\d+)$']
views.py:
def blog_detail(request, id):
# post request from the url
return render(request, "BlogHome/pages/post.html")
post = Post.objects.get(id)
# Next Post
try:
Next_Post_id = (post.id + 1)
Next_Post = Post.objects.get(id=Next_Post_id)
except ObjectDoesNotExist:
Next_Post = None
# Previous Post
try:
Previous_Post_id = (post.id - 1)
Previous_Post = Post.objects.get(id=Previous_Post_id)
except ObjectDoesNotExist:
Previous_Post = None
context = {'post': post, 'Next_Post': Next_Post, 'Previous_Post': Previous_Post}
return render(request, "BlogHome/pages/post.html", context)
urls.py:
urlpatterns = [
url(r'^$', views.blog_list),
url(r'^(?P<id>\d+)$', views.blog_detail, name='blog_detail_url'),
]
post.html:
{% extends "BlogHome/includes/WELL.html" %}
{% block content %}
<script>
document.title = "Pike Dzurny | {{post.title}}"
</script>
<div class="container-fluid text-center">
<center>
<div class="well" id="WellPost">
<div class="container-fluid">
<h2 align="center" id="TitleText">{{post.title}}</h2>
<h3 align="center" id="BodyText">{{ post.date|date:"m-d"}}</h3>
<h3 align="left">{{ post.body|safe }}</h3>
{% if Next_Post is defined and Previous_Post is defined %}
<ul class="pager">
<li class="previous"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span
aria-hidden="true">←</span> Older</a></li>
<li class="next "><a href="{% url 'blog:blog_detail_url' Next_Post.id %}">Newer <span
aria-hidden="true">→</span></a></li>
<h1>1</h1>
</ul>
{% elif Next_Post is defined %}
<ul class="pager">
<li class="previous disabled"><a href=""><span aria-hidden="true">←</span> Older</a></li>
<li class="next"><a href="{% url 'blog:blog_detail_url' Next_Post.id %}">Newer <span aria-hidden="true">→</span></a>
</li>
</ul>
<h1>2</h1>
{% elif Previous_Post is defined %}
<ul class="pager">
<li class="previous"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span aria-hidden="true">←</span>
Older</a></li>
<li class="next disabled"><a href="">Newer <span aria-hidden="true">→</span></a></li>
</ul>
<h1>3</h1>
{% else %}
<ul class="pager">
<li class="previous disabled"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span aria-hidden="true">←</span> Older</a></li>
<li class="next disabled"><a href="{% url 'blog:blog_detail_url' Next_Post.id %}">Newer <span aria-hidden="true">→</span></a></li>
</ul>
<h1>4</h1>
{% endif %}
</div>
</center>
</div>
{% endblock %}
錯誤發生在post.html中的第22行(<li class="previous"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span aria-hidden="true">←</span> Older</a></li>
)。我猜,我非常建立jinja2 href?
錯誤現在是'反向'blog_detail_url'參數'()'和關鍵字參數'{'id':''}'找不到。嘗試1種模式:['blog /(?P \\ d +)$'] ' –
@PikeD。你會想傳遞'id'而不是對象,所以將'next_post_id'粘貼到你的上下文中並使用它。 – denvaar
啊,我沒有注意到。謝謝! –