Reverse for 'post_detail' with arguments '('chempion',)' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$']
as soon as I add function and view to templates I catch this error
view.py
def post_detail(request, category_slug, slug):
post = get_object_or_404(Post, slug=slug)
try:
next_post = post.get_next_by_date_added()
except Post.DoesNotExist:
next_post = None
try:
previous_post = post.get_previous_by_date_added()
except Post.DoesNotExist:
previous_post = None
context = {
'post': post,
'next_post': next_post,
'previous_post': previous_post
}
return render(request, 'post_detail.html', context)
urls.py
path('<slug:category_slug>/<slug:slug>/', post_detail, name='post_detail'),
path('<slug:slug>/', category_detail, name='category_detail'),
post detail.html
{% if next_post %}
<a href="{% url 'post_detail' next_post.slug %}">Next</a>
{% else %}
This is the last post!
{% endif %}
The post_detail
view requires two slugs: one of slug for the category, and one for the post.
If your Post
model for example has a ForeignKey
to the Category
model, you can reference this with:
<a href="{% url 'post_detail' next_post.category.slug next_post.slug %}">Next</a>
In your view, you might want to check both the slug for the category and for the post, so:
def post_detail(request, category_slug, slug):
post = get_object_or_404(Post, category__slug=category_slug, slug=slug)
# …