姜戈 |我想向 'AnonymousUser' 显示页面,即使我在 views.py 中使用 request.user

Django | I want to show the page to 'AnonymousUser' even though I'm using request.user in views.py

我想向所有用户显示该页面,即使他们没有登录,但因为我在 views.py 中使用 request.user,这是不可能的。

有办法处理吗?

views.py:

class ServerView(View):
def get(self, request, server_tag):
    server = Server.objects.get(tag=server_tag)
    posts = server.posts.all()
    is_following = False
    relation = ServerFollow.objects.filter(server=server, user=request.user)
    if relation.exists():
        is_following = True
    return render(request, 'servers/server.html', {'server':server, 'posts':posts, 'is_following':is_following})

只需检查请求用户是否已通过身份验证。在此基础上,您可以实现链式过滤。

class ServerView(View):
    def get(self, request, server_tag):
        server = Server.objects.get(tag=server_tag)
        posts = server.posts.all()
        is_following = False
        qs = ServerFollow.objects.filter(server=server)
        if qs and request.user.is_authenticated():
            qs = qs.filter(user=request.user)
        if qs:
            is_following = True
        return render(request, 'servers/server.html', {'server':server, 'posts':posts, 'is_following':is_following})