Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

django - Double filter on detail view

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...