MASIGNASUKAv102
6510051498749449419

Get the current logged in user in Django models

Get the current logged in user in Django models
Add Comments
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)
 


 

Adarshreddy Adelli

As an Engineering Lead with deep expertise in Artificial Intelligence, Cybersecurity, and Systems Architecture, I guide teams in building innovative, secure, and scalable solutions.I am passionate about tackling challenging technical problems, fostering engineering excellence, and delivering solutions that balance innovation, security, and performance. I actively share knowledge through blogging and community engagement, contributing to the advancement of AI and cybersecurity practices.