I'm a beginner in developer of django.
I want to create a template tag on homepage of my blog and link to article page of my blog.
Here is my template tag:
{% url 'post_detail' pk=post.pk article_id=photo.article_id %}
but cause the error:
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>[^/]+)/$']
I try (pk and article_id) = 1,2,3... and so on.It can function.
Here is my code:
home page 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')
Change your path:
path('post/<int:pk>/<int:article_id>/', views.post_detail, name='post_detail')
As @Walucas commented on your question, you reference a 'post' object in your template that hasn't been passed from your view as context.
{% url 'post_detail' pk=post.pk article_id=photo.article_id %}
^
perhaps you mean:
{% url 'post_detail' pk=article.pk article_id=photo.article_id %}
^
easily missed.
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>[^/]+)/$']
When you read error message, you can understand your mistake.
['post/(?P<pk>[^/]+)/$', 'post/(?P<pk>[^/]+)/(?P<article_id>[^/]+)/$']
Meaning of the above output, you should use 'post' keyword instead of 'article'.
{% url 'post_detail' pk=post.pk something=post.something %}
I think you should check your other python files.
Your views.py file didn't contain 'views. post_detail'.
'views. post_detail'.
If you make a change like the codes above, I think you can solve your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.