错误:
django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '(2018, 11, 6, 'another post')' not found.
1 pattern(s) tried: ['blog\\/(?P<year>[0-9]+)\\/(?P<month>[0-9]+)\\/(?P<day>[0-9]+)\\/(?P<post>[-a-zA-Z0-9_]+)\\/$']
下面是我的template/blog/base.html文件:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>My blog</h2>
<p>This is my blog</p>
</div>
</body>
</html>
下面是我的template/blog/post/list.html文件:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts%}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
和博客/urls文件:
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
#post views
path('',views.post_list,name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',
views.post_detail,
name='post_detail'),
]
博客/视图文件:
from django.shortcuts import render,get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request,'blog/post/list.html',{'posts':posts})
def post_detail(request,year,month,day,post):
post = get_object_or_404(Post,slug=post,
status='published',
published__year=year,
published__month=month,
published__day = day)
return render(request,'blog/post/detail.html',{'post':post})
请帮我解决这个问题,我会很高兴,因为我已经被困在这个问题上一周了!
发布于 2018-11-06 18:24:21
嗯,正如你所指出的,你使用Django by example
书,那么你的get_absolute_url
是:
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.month,
self.publish.day,
self.slug])
书中有一个创建Post
对象的示例:
您输入了错误的内容,输入的不是slug='another-post'
,而是slug='another post'
。
什么是slug
。来自Django docs
slug -匹配由ASCII码字母或数字以及连字符和下划线字符组成的任何辅助字符串。例如,构建您的第一个django站点。
如您所见,slug中不允许有空格。
您可以删除包含错误的slug的帖子并创建另一个对象。
或者您可以直接在shell中修复现有的post:
from django.utils.text import slugify
post = Post.objects.get(pk=id_of_your_post) # replace with int number
fixed_slug = slugify(post.slug)
post.slug = fixed_slug
post.save()
https://stackoverflow.com/questions/53169225
复制相似问题