Search code examples
djangodjango-rest-frameworkdjango-middleware

Django Middleware to Extend self.request for a social media apps


We know in Django, we can access to too many instances in self.request like self.request.user, self.request.data, self.request.authenticator etc

I am trying to get self.request.mygroup writing custom middleware

this is my models

from django.contrib.auth.models import User
from django.db import models
class Person(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False
    )
    auth_user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='auth_user',
    )

class Group(models.Model):
    members = models.ManyToManyField(
        Person,
        related_name='group_members'
    )

I wrote this middleware and it is working fine:

class GroupMiddleWare(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        person = Person.objects.filter(
            auth_user__id=request.user.id
        ).first()
        mygroup = Group.objects.filter(
            members__alias__in=[person.alias]
        )
        request.mygroup = mygroup.first()
        response = self.get_response(request)
        return response

Above middleware working fine but the problem is when I visit from incognito mode, I mean when I am not logged in, it throws me an error like AnonymouseUser doesn't have attribute self.request.user

to handle this, I tried writing condition like if self.request.user.is_authenticated: but it occurs another error as same. I guess I crafted the middleware wrongly, Can anyone help me to extend self.request to get my own instance like self.request.mygroup?

I am not getting what is the right way to write a middleware, i am very new in middleware

I want self.request.mygroup should retun only authinticated user's group


Solution

  • I am not a Django user, but it sounds like you are checking the wrong thing.

    self.request.user.is_authenticated

    is also throwing an error because they are not authenticated so the user is null, so maybe try checking if self.request.user is null? and only checking the next bit if it is not null.

    From The Documentation

    django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:

    id is always None.
    username is always the empty string.
    get_username() always returns the empty string.
    is_staff and is_superuser are always False.
    is_active is always False.
    groups and user_permissions are always empty.
    is_anonymous() returns True instead of False.
    is_authenticated() returns False instead of True.
    set_password(), check_password(), save() and delete() raise NotImplementedError.
    

    Possibly also here: django profies and request.user - error