Skip to content
Advertisement

Why am i getting NoReserverMatch at /?

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

from django.contrib import admin
from django.urls import path,re_path
from blog import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.post_list_view),
    re_path(r'^blog/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/(?P<post>[-w]+)/$',
    views.post_detail_view,name='post_details'),

This is my models.py (used for reverse url)

def __str__(self):
    return self.title
def get_absolute_url(self):
    return reverse('post_details',args=[self.publish.year,self.publish.strftime('%m'),
    self.publish.strftime('%d'),self.slug])

This is my post_list.html

{%extends 'blog/base.html'%}
{%block title_block%} Sentamil's Blog Home Page{%endblock%}
  {%block content%}
  <h1>My Blog</h1>
  {%for post in post_list%}

  <a href="{{post.get_absolute_url}}"> <h2>{{post.title}}</h2></a>
  <p id='date'>Published on {{post.publish}} by {{post.author|title}}</p>
  {{post.body|truncatewords:30|linebreaks}}
  {%endfor%}
  {%endblock%}

Advertisement

Answer

This is old method to for routing a URL

re_path(r'^blog/(?P<year>d{4})/(?P<month>d{2})/(?P<day>d{2})/(?P<post>[-w]+)/$',
    views.post_detail_view,name='post_details'),

In DJANGO 3.1 this method is used for routing a URL as i did below and it is understandable method

re_path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail_view,name='post_details'),

And you have to change your “Canonical URL” as i did below

def get_absolute_url(self):
 return reverse('blog:post_detail',
 args=[self.publish.year,
 self.publish.month,
self.publish.day, self.slug])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement