I am new to Python and trying to develop a simple blog application.I am getting NoReverseMatch at / error while trying canonical url. Tried different solution to fix this but i am getting help for django versions which are old. Please help me with a solution for updated Django version.
ERROR: Reverse for ‘post_details’ with arguments ‘(2020, ’08’, ’15’, ‘indian-software-industry’)’ not found. 1 pattern(s) tried: [‘blog/(?Pd{4})/(?Pd{2})/(?Pd{2})/(?P[-w]+)/$’]
This is my urls.py
JavaScript
x
9
1
from django.contrib import admin
2
from django.urls import path,re_path
3
from blog import views
4
urlpatterns = [
5
path('admin/', admin.site.urls),
6
path('',views.post_list_view),
7
re_path(r'^blog/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/(?P<post>[-w]+)/$',
8
views.post_detail_view,name='post_details'),
9
This is my models.py (used for reverse url)
JavaScript
1
6
1
def __str__(self):
2
return self.title
3
def get_absolute_url(self):
4
return reverse('post_details',args=[self.publish.year,self.publish.strftime('%m'),
5
self.publish.strftime('%d'),self.slug])
6
This is my post_list.html
JavaScript
1
12
12
1
{%extends 'blog/base.html'%}
2
{%block title_block%} Sentamil's Blog Home Page{%endblock%}
3
{%block content%}
4
<h1>My Blog</h1>
5
{%for post in post_list%}
6
7
<a href="{{post.get_absolute_url}}"> <h2>{{post.title}}</h2></a>
8
<p id='date'>Published on {{post.publish}} by {{post.author|title}}</p>
9
{{post.body|truncatewords:30|linebreaks}}
10
{%endfor%}
11
{%endblock%}
12
Advertisement
Answer
This is old method to for routing a URL
JavaScript
1
3
1
re_path(r'^blog/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/(?P<post>[-w]+)/$',
2
views.post_detail_view,name='post_details'),
3
In DJANGO 3.1 this method is used for routing a URL as i did below and it is understandable method
JavaScript
1
2
1
re_path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail_view,name='post_details'),
2
And you have to change your “Canonical URL” as i did below
JavaScript
1
6
1
def get_absolute_url(self):
2
return reverse('blog:post_detail',
3
args=[self.publish.year,
4
self.publish.month,
5
self.publish.day, self.slug])
6