【发布时间】:2017-01-22 06:51:29
【问题描述】:
在我的博客上,我正在尝试创建一个 URL 寻呼系统,我可以在其中通过 Post 模型的 ID 链接到上一篇和下一篇文章。现在,每次我尝试访问博客网页时都会收到此错误:
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 (<li class="previous"><a href="{% url 'blog:blog_detail_url' Post.id %}"><span aria-hidden="true">&larr;</span> Older</a></li>) 的第 22 行。我猜,我不正确地设置了 jinja2 href?
【问题讨论】: