我写简单的Django-blog, django.VERSION - (2,0,1,'final',0)
但我收到错误,不明白如何解决它。
NoReverseMatch at /posts/
Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1
pattern(s) tried: ['posts\\/(?P<id>\\d)/$']
并且
Error during template rendering
In template
djangoblog/posts/templates/posts/base.html, error at line 0
Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1
pattern(s) tried: ['posts\\/(?P<id>\\d)/$']
1 {% load staticfiles %}
2 <!DOCTYPE html>
3 <html lang="en">
4 <head>
5 <meta charset="UTF-8">
6 <title>{% block head_title %}
7 Django-blog! {% endblock head_title %}</title>
8 <link rel="stylesheet"
9
models.py
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
image = models.FileField(null=True, blank=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False,
auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"id": self.id})
class Meta:
ordering = ['-timestamp', '-updated']
我在views.py中的def看起来像
def post_list(request):
queryset_list = Post.objects.all()
paginator = Paginator(queryset_list, 5)
page = request.GET.get('page')
queryset = paginator.get_page(page)
context = {
'object_list': queryset,
'title': 'List'
}
return render(request, 'posts/post_list.html', context)
urls.py urlpatterns中的看起来像
urlpatterns = [
re_path('^$', post_list, name='list'),
re_path('^create/$', post_create),
re_path(r'^(?P<id>\d)/$', post_detail, name='detail'),
re_path(r'^(?P<id>\d)/edit/$', post_update, name='update'),
re_path(r'^(?P<id>\d)/delete/$', post_delete),
]
非常感谢你。 如果您需要其他信息 - 请告诉我。
答案 0 :(得分:0)
Django正在寻找一个你尚未创建的名为'detail'
的网址,因此会抛出错误。
您需要创建一个类似post_detail
的视图,并将其包含在名称为detail
的网址中,例如
re_path('posts/(?P<id>\d+)/$', post_detail, name='detail')