I have this post_list.html file: (Ignore the second 'blog:post_detail' url)
{% for post in post_list %}
<h1><a href="{% url 'blog:post_detail' post.pk %}">{{ post.title }}</a></h1>
<div class="date">
<p>Published on: {{post.published|date:"D M Y"}}</p>
</div>
<a href="{url 'blog:post_detail' post.pk}">Comments: {{post.approve_comments.count}}</a>
{% endfor %}
And in the urls.py I am trying to use re_path in the following way:
re_path(r'^posts/<int:pk>/$', views.PostDetailView.as_view(), name='post_detail'),
When I run the server I am getting NoReverseMatch at / error:Reverse for 'post_detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/<int:pk>/$']
However if I replace re_path with url and <int:pk> with (?P<pk>\d+) it works perfectly:
url(r'^posts/(?P<pk>\d+)/$', views.PostDetailView.as_view(), name='post_detail'),
because your django is not 2.0+
django 2.0 recommended use path
path(r'^posts/<int:pk>/$', views.PostDetailView.as_view(), name='post_detail')
if you want to use regular expression, like django<2.0
re_path(r'^posts/(?P<pk>\d+)/$', views.PostDetailView.as_view(), name='post_detail'),
url(r'^posts/(?P<pk>\d+)/$', views.PostDetailView.as_view(), name='post_detail'),
You're using the wrong function. re_path is an alias for url, so it uses the old regex syntax. If you want to use the new syntax, use path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With