【发布时间】:2020-10-26 09:39:37
【问题描述】:
我是 django 开发人员的初学者。
我想在我的博客主页上创建一个模板标签,并链接到我博客的文章页面。
这是我的模板标签:
{% url 'post_detail' pk=post.pk article_id=photo.article_id %}
但会导致错误:
NoReverseMatch at /
Reverse for 'post_detail' with keyword arguments '{'pk': '', 'article_id': ''}' not found. 2 pattern(s) tried: ['post/(?P<pk>[^/]+)/$', 'post/(?P<pk>[^/]+)/(?P<article_id>[^/]+)/$']
我试试 (pk and article_id) = 1,2,3 ...等等。它可以运行。
这是我的代码:
主页html:
<div class="story">
{% for article in article %}
<div>
<div>
<h3><b>{{ article.title }}</b></h3>
<h5>{{ article.created_at }}</h5>
</div>
<div>
<p>{{ article.content }}</p>
<div>
<div>
<p><button type="button" onclick="location.href='{% url 'post_detail' pk=post.pk article_id=photo.article_id %}'"><b>READ MORE »</b></button></p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
view.py:
def home(request):
article = Article.objects.all()
photo = Picture.objects.all()
return render(request, 'home.html', {'article':article,'photo':photo} )
def post_detail(request,pk,article_id):
post = Article.objects.get(pk=pk)
photo = Picture.objects.get(article_id=article_id)
return render(request,"post.html",{"post":post , "photo":photo})
url.py:
from blog.views import home,post_detail
path('', home)
path('post/<pk>/<article_id>/', post_detail, name='post_detail')
【问题讨论】:
-
您的
post对象在您的模板上来自哪里?