[Django]-Django middleware to determine user's group in a session

1👍

In general it looks good. You can make it a bit more Pythonic though:

class SetGroupMiddleware(object):
    def process_request(self, request):
        if 'thegroup' not in request.session:
            if not request.user.is_anonymous():
                groups = request.user.groups.all()
                if groups:
                    request.session['thegroup'] = str(groups[0].name)
            else:
                request.session['thegroup'] = None # for completeness

0👍

It looks approximately correct (not having tested it). One thing to note is that your middleware must occur after django.contrib.sessions.middleware.SessionMiddleware in the MIDDLEWARE_CLASSES list, otherwise the session won’t have been setup for you at the time you try to reference it.

0👍

Well, as I commented in Steve Losh’s answer , that code doesn’t work as intended.

I modified it as follows and it seems to be OK till now: –

class SetGroupMiddleware(object):
    def process_request(self, request):
        if not request.user.is_anonymous():
            if 'thegroup' not in request.session:
                groups = request.user.groups.all()
                if groups:
                    request.session['thegroup'] = str(groups[0].name)

Leave a comment