python - 为什么我在 / 处得到 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%}
解决方案
这是路由 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])
推荐阅读
- powershell - Chocolatey 不使用 PowerShell cmdlet
- python - 创建一个比较两行的新列
- python - 使用python多次迭代/循环通过json文件
- python - 使用pip安装模块,Python找不到...这两个路径是否不同,如果是,如何将模块放入正确的位置?
- python - Python GetModule 错误中的 comtypes:UnicodeDecodeError:'utf-8' 编解码器无法解码位置 621 中的字节 0x92:无效的起始字节
- elasticsearch - Elasticsearch - 计算嵌套字段中元素的出现次数
- sql - 触发器几乎没有错误帮助我解决这个问题
- matplotlib - 如何在多个图中隐藏轴
- android - 如何为所有新项目配置项目级别的 build.gradle?
- apigee - Apigee:无法通过 Management Server 进行身份验证