没有帖子匹配给定查询,django blog

x8diyxa7  于 2023-01-10  发布在  Go
关注(0)|答案(1)|浏览(100)

模型中一切正常,但当我尝试检索对象时,显示错误“No Post matches the given query.”。我不知道显示此错误的问题是什么?

**Model**
class Post(CoreField):
    ....
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    tags = TaggableManager()
    publish = models.DateTimeField(default=timezone.now)

    def get_absolute_url(self):
        return reverse('news:post_detail',
                       args=[self.publish.year,
                             self.publish.month,
                             self.publish.day,
                             self.slug])

**url**
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),

**views**
def post_detail(request, year, month, day, post):
    single_post = get_object_or_404(Post,
                                    publish__year=year,
                                    publish__month=month,
                                    publish__day=day,
                                    slug=post
                                    )
    # List of active comments for this post
    comments = post.comments.filter(active=True)
    # Form for users to comment
    form = CommentForm()
    return render(request, 'news/post_detail.html', {'post': single_post, 'comments': comments, 'form': form})

当我移除“int:year/int:month/int:day/”表单URL时,它可以工作。但是当我传递“int:year/int:month/int:day/slug:post/”时,它不工作。
问题是什么,发生在哪里?

vxf3dgd4

vxf3dgd41#

在post_detail视图中,我认为应该将“slug”作为参数传递给视图,而不是“post”,因为post不是模型字段,也没有在任何地方定义它,并且“slug=post”kwarg应该颠倒以避免更多错误,因此post_detail视图应该如下所示:

def post_detail(request, year, month, day, slug):
    single_post = get_object_or_404(Post,
                                    publish__year=year,
                                    publish__month=month,
                                    publish__day=day,
                                    post=slug
                                    )

相关问题