Double filter on detail view

余生颓废 提交于 2019-12-12 06:51:29

问题


I'm trying to create a detail view using function based view. This view must make visible only the already published posts and the non draft posts.

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)

But when I use this I see this error message:

name 'post_filter' is not defined

How I can solve?

NB: the view works fine in that way

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)

回答1:


Based on the information given, I would recommend using the following approach.

Use a single filter to get the criteria for your blog post and raise an error if it doesn't exists.

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)



来源:https://stackoverflow.com/questions/57043003/double-filter-on-detail-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!