我正在尝试使用基于函数的视图创建详细视图。此视图必须仅显示已发布的帖子和非草稿的帖子。
def singlePost(request, slug_post, slug_category):
post_category = get_object_or_404(BlogCategory, slug_category=slug_category)
if post_filter == BlogPost.objects.filter(draft=True):
raise PermissionDenied
if post_filter == BlogPost.objects.filter(publishing_date__gt=datetime.datetime.now()):
raise PermissionDenied
else:
post_filter == BlogPost.objects.all()
post_details = get_object_or_404(post_filter, slug_post=slug_post)
category_post_details = BlogPost.objects.filter(post_category=post_category)
context = {
"post_category": post_category,
"post_details": post_details,
"category_post_details": category_post_details,
}
template = 'blog/reading/single_post.html'
return render(request, template, context)
但是当我使用它时,我看到以下错误消息:
名称'post_filter'未定义
我该如何解决?
注意:以这种方式视图工作正常
def singlePost(request, slug_post, slug_category):
post_category = get_object_or_404(BlogCategory, slug_category=slug_category)
post_details = get_object_or_404(BlogPost, slug_post=slug_post)
category_post_details = BlogPost.objects.filter(post_category=post_category)
context = {
"post_category": post_category,
"post_details": post_details,
"category_post_details": category_post_details,
}
template = 'blog/reading/single_post.html'
return render(request, template, context)
答案 0 :(得分:1)
根据给出的信息,我建议使用以下方法。
使用单个过滤器获取博客文章的条件,如果不存在,则会引发错误。
post_filter = BlogPost.objects.filter(draft=False,
publishing_date__lt=datetime.datetime.now()):
if not post_filter.exists():
raise PermissionDenied
else:
post_details = get_object_or_404(post_filter, slug_post=slug_post)