首页 > 解决方案 > 为什么我在 / 处得到 NoReserverMatch?

问题描述

我是 Python 新手,正在尝试开发一个简单的博客应用程序。我在尝试规范 url 时遇到 NoReverseMatch / 错误。尝试了不同的解决方案来解决这个问题,但我正在为旧的 django 版本获得帮助。请帮助我为更新的 Django 版本提供解决方案。

错误:未找到带有参数“(2020,'08','15','indian-software-industry')'的'post_details'的反向。尝试了 1 种模式:['blog/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P\[-\w] +)/$']

这是我的 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'),

这是我的 models.py(用于反向 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])

这是我的 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%}

标签: pythondjango

解决方案


这是路由 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'),

在 DJANGO 3.1 中,此方法用于路由 URL,如下所示,这是可以理解的方法

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

你必须改变你的“规范网址”,就像我在下面所做的那样

def get_absolute_url(self):
 return reverse('blog:post_detail',
 args=[self.publish.year,
 self.publish.month,
self.publish.day, self.slug])

推荐阅读