Home > Net >  Django | I want to show the page to 'AnonymousUser' even though I'm using request.use
Django | I want to show the page to 'AnonymousUser' even though I'm using request.use

Time:06-03

I want to show the page to all users even if they are not logged in but because im using request.user in views.py this is not possible.

Is there anyway to handle this?

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})

CodePudding user response:

Just check if the request user is authenticated. Based on that you can implement chained filtering.

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})
  • Related