我正在使用Python和Django开发一个简单的博客。在我的主页上,我显示3个最新帖子,然后显示所有帖子。至此,我的博客正在运行。但是我添加了一个链接“显示更多”或“显示文章”,以单独在新页面中显示帖子,但是在加载页面时出现以下错误:
找不到与关键字参数“ {'pk':''}'”的“ post_detail”反向匹配的NoReverseMatch。尝试了1个模式:['post /(?P [0-9] +)/ $']
PS:我正在学习本教程in french(这是英语,但是in english here有点不同。请注意,我只是在启动Python和Django:)>
这是我的代码:
{% extends 'blog/base.html' %}
{% block latestsnews %}
{% for latest in latests %}
<article class="lastnews">
<h4>{{ latest.title }}</h4>
<h5 class="lastestcategory">{{ latest.category }}</h5>
<p class="bodysmall">{{ latest.text|truncatewords:10 }}</p>
<div>
<p class="date">{{ latest.published_date }}</p>
<p class="showmore"><a href="{% url 'post_detail' pk=post.pk %}">Show more</a></p>
</div>
</article>
{% endfor %}
{% endblock %}
{% block posts %}
{% for post in posts %}
<article class="post">
<header class="postheader">
<h4>{{ post.title }}</h4>
<p class="info">{{ post.category }}, {{ post.published_date }}</p>
</header>
<p class="bodyregular">{{ post.text|linebreaksbr }}</p>
<footer class="postfooter">
<p class="author">Author: {{ post.author }}</p>
<p class="showarticle"><a href="{% url 'post_detail' pk=post.pk %}">Show article</a></p>
</footer>
</article>
{% endfor %}
{% endblock %}
from django.shortcuts import render
from django.utils import timezone
from .models import Category, Post
from django.shortcuts import render, get_object_or_404
def category_list(request):
categories = Category.objects.all()
return render (request, 'blog/post_list.html', {'categories': categories})
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
latests = Post.objects.filter(published_date__lte=timezone.now()).reverse()[:3]
return render(request, 'blog/post_list.html', {'posts': posts, 'latests': latests})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'),
]
{%url'post_detail'pk = post.pk%} ,在模板上
from django.shortcuts导入视图上的渲染get_object_or_404
** def post_detail(请求,pk):
post = get_object_or_404(Post,pk = pk)
在视图上返回渲染(请求,'blog / post_detail.html',{'post':发布})**
在网址上url(r'^ post /(?P [0-9] +)/ $',views.post_detail,name ='post_detail')
谢谢!
答案 0 :(得分:1)
在模板中编写:
{% for latest in latests %}
<!-- ... -->
<p class="showmore"><a href="{% url 'post_detail' pk=post.pk %}">Show more</a></p>
<!-- ... -->
{% endfor %}
但是第一次出现是在{% for post in posts %}
循环之前 ,那时没有post
变量,但是有latest
变量(因为它位于{% for latest in latests %}
循环中),因此您可能希望将其替换为:
<p class="showmore"><a href="{% url 'post_detail' pk=latest.pk %}">Show more</a></p>
答案 1 :(得分:0)
如果它是一个Heroku Web应用程序,请运行heroku运行python manage.py createsuperuser,然后添加一个帖子,如果它的本地项目只是运行python manage.py createsuperuser并添加一个帖子
只需转到管理员并添加这些内容