Search code examples
djangodjango-rest-frameworkdjango-middleware

Django writing Middleware to extend self.request


I am very new to writing custom middleware in Django.

We know in Django, there is built-in self.request. in self.request, there are too many instances like self.request.user, self.request.data, self.request.authenticator etc

I am trying to add self.request.mycustom; in self.request.mycustom, I want to get my models MyCustom instance.

This is My Models:

from django.contrib.auth.models import User

class MyCustom(models.Model):
    auth_user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='auth_user',
    )

I am trying to write the middleware but not getting how to write this.

this is my attempt to write:

class MessMiddleWare(obect):
    def precess_view(request):
        mycustom = MyCustom.objects.filter(id=request.user.pk)
        request.mycustom = mycustom

Can anyone help me to achieve this?

I just I want to get self.request.mycustom


Solution

  • Simply do:

    from django.shortcuts import get_object_or_404
    
    ...
    
    class MessMiddleWare(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            mycustom = MyCustom.objects.filter(id=request.user.pk)
            # Instead of using filter, consider doing (if it fits your usecase):
            # mycustom = get_object_or_404(MyCustom, pk=request.user.pk)
            request.mycustom = mycustom
            response = self.get_response(request)
            return response
    

    Do not forget to add your middleware in MIDDLEWARE of settings.py.


    Note that it should be object and not obect.


    Read more about writing custom middlewares in Django's official documentation.