Django Get Current User Example
In this tutorial, I will show you django get current user example. This tutorial will give you simple example of django views get current user. I would like to show you django get current user middleware. step by step explain django get current user in view.
In this tuts, First of all we can check you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.
let's see below simple example with output:Example views.py
from django.shortcuts import render from django.http import HttpResponse def index(request): current_user = request.user print(current_user.id) return HttpResponse('')
So, request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:Output
if request.user.is_authenticated: # Do something for authenticated users. else: # Do something for anonymous users.
I Hope It will help you....