Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django (?P<pk>\d+) vs <int:pk>

Tags:

python

django

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'),
like image 450
Shubham Khandalkar Avatar asked Dec 24 '22 07:12

Shubham Khandalkar


2 Answers

because your django is not 2.0+

django >=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'),

django<2.0

url(r'^posts/(?P<pk>\d+)/$', views.PostDetailView.as_view(), name='post_detail'),
like image 121
JayTam Avatar answered Jan 12 '23 05:01

JayTam


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.

like image 34
Daniel Roseman Avatar answered Jan 12 '23 05:01

Daniel Roseman