Tuesday, May 4, 2021
#Django 100 days
You can get the currently logged-in user in views of Django easily using request.user. It might be time-consuming if your project frequently deals with the logged-in user. Now let's make it much easy using Django middleware.
Create a current_user.py file under the middleware folder in your Django app and add the below code. You can also do this in the main project folder.
from threading import local
from django.utils.deprecation import MiddlewareMixin
_user = local()
class CurrentUserMiddleware(MiddlewareMixin):
def process_request(self, request):
_user.value = request.user
def get_current_user():
try:
return _user.value
except AttributeError:
return None
Now add the middleware in settings.py
<app_name>.middleware.current_user.CurrentUserMiddleware'
Finally you can get the current user using the following parameter.
from django.db import models
from django.conf import settings
from TGroup.middleware import current_user
import uuid
class TravelGroup(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=100, null=False)
creator = models.CharField(settings.AUTH_USER_MODEL,
null=True,
max_length=25,
blank=True,
editable=False,
default=current_user.get_current_user) # current_user.get_current_user
created_date = models.DateTimeField(auto_now_add=True,
blank=True,
null=True)
0 Response to Get the current logged in user in Django models
Comments are personally moderated by our team. Promotions are not encouraged.
Post a Comment