django 我想创建评论部分,只能登录用户可以使用,但我有这个问题

2cmtqfgy  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(124)

我收到错误:
无法解包不可迭代的bool对象

profile = Profile.objects.get(Profile.user == request.user)

这是我的models.py在帐户应用程序和博客应用程序:
第一次
这是我的网站views.py,欢迎大家发表意见:

def post_detail(request, year, month, day, slug):
    post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day)
    tags = Tag.objects.all()
    tagsList = []
    for tag in post.tags.get_queryset():
        tagsList.append(tag.name)
    profile = Profile.objects.get(Profile.user == request.user)
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.profile = profile
            new_comment.post = post
            new_comment.save()
            
            return redirect('post_detail', slug=post.slug)
    else:
        comment_form = CommentForm()
        
    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3]
        
    return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags})

这个问题有什么解决办法吗?

8mmmxcuj

8mmmxcuj1#

假设您只需要获取一个配置文件示例,即当前登录用户的配置文件,那么您可以用途:

profile = Profile.objects.get(user=request.user)

或:

get_object_or_404(Profile, user=request.user)

要将视图限制为仅由登录用户访问,请使用@login_required装饰器,如下所示:

@login_required(login_url='/accounts/login/') # you can give any login_url you want.
def post_detail(request, year, month, day, slug):
    #...

相关问题