错误:
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_]+)\\/$']
这是我的templates / 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>
这是我的模板/博客/帖子/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 %}
以及博客/网址文件:
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})
请帮助我解决问题,我会很高兴,因为我被困了一周!
答案 0 :(得分:1)
好吧,正如您指出的那样,您使用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])
您输入了错误的内容,而不是输入slug='another-post'
而不是slug='another post'
。
什么是slug
。来自Django docs:
子弹-匹配由ASCII字母或数字组成的任何子弹字符串, 加上连字符和下划线字符。例如, building-your-1st-django-site 。
如您所见,在符号中不允许有空格。
您可以删除没有正确提示的帖子,然后创建另一个对象。
或者您可以直接在shell中修复现有帖子:
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()