【发布时间】:2020-11-16 23:27:02
【问题描述】:
即使我在数据库中只创建了一篇文章,我也会在 pk 20 中收到此 NoReverseMatch 错误。 它没有按照应有的方式列出所有帖子,并给出了这个错误。
这是屏幕截图
models.py
from django.db import models
from django.urls import reverse
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
created_on = models.DateTimeField(default=timezone.now)
published_on = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_on = timezone.now()
self.save()
def approve_comments(self):
return self.comments.filter(approve_comment=True)
def get_absolute_url(self):
return reverse("post_detail", kwargs={"pk": self.pk})
# def __str__(self):
# return self.author
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=100)
text = models.TextField()
created_on = models.DateTimeField(default=timezone.now)
approve_comment = models.BooleanField(default=False)
def approve(self):
self.approve_comment = True
self.save()
def get_absolute_url(self):
return reverse("post_list")
# def __str__(self):
# return self.text
def __str__(self):
return self.text
urls.py
from django.urls import path
from blog import views
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'),
path('post/new/', views.PostCreateView.as_view(), name='post_new'),
path('post/<int:pk>/delete/', views.PostDeleteView.as_view(), name='post_delete'),
path('post/<int:pk>/update/', views.UpdatePostView.as_view(), name='post_update'),
path('draft/', views.DraftListView.as_view(), name='post_draft_list'),
path('post/<int:pk>/publish/', views.PostPublish, name='post_publish'),
path('post/<int:pk>/comment/', views.add_comment_to_post, name='comment_new'),
path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'),
path('comment/<int:pk>/remove/', views.remove_comment, name='comment_delete')
]
views.py(仅列表视图)
class PostListView(ListView):
model = Post
context_object_name = 'post_list_content'
template_name = 'blog/post_list.html'
def get_queryset(self):
return Post.objects.filter(published_on__lte=timezone.now()).order_by('-published_on')
post_list.html(出现错误的模板)
{% extends 'blog/base.html' %}
{% load static %}
{% block body_block %}
<div class="container jumbotron">
<h1>Welome to Social Blog</h1>
{% for post in post_list_content %}
<div class='post'>
<h1><a href="{% url 'post_list' pk=post.pk %}"> {{post.title}} </a></h1>
</div>
<div class='date'>
<p>Published on : {{post.published_on|date:"D M Y"}}</p>
</div>
<a href={% url "post_detail" %} >Comments: {{ post.approve_comments.count }} </a>
{% endfor %}
</div>
{% endblock body_block %}
谁能告诉我究竟是什么错误呢?
【问题讨论】:
标签: python-3.x django django-models django-views django-templates