0

My use case is that I want different users to be able to work on their own projects and be restricted from seeing material in other projects, even in the Admin site. There are a number of models that ought to be filtered back to 'project' - for example a concrete Answer extends the Abstract class Answer, which has question as a foreign key and Question which have project as a foreign key.

My plan was to modify the default ModelManager get_queryset() and return a queryset with a filter something like: Project.objects.filter(group__in=user.groups.all())

The challenge is for the ModelManager to reliably know which user is calling it, without changing the signature every time a queryset is produced. I found this solution, which looks extremely smooth:

Middleware maintaining a dict of requests indexed by the thread handling them

But its from 2010 and I'm not sure how much Django, Python, thread-handling, the security landscape etc may have changed in the mean time. Is there now a preferred way to do this, with sessions perhaps?

(related problem here: Django custom manager request object/current user)

Atcrank
  • 439
  • 3
  • 11

1 Answers1

0

Translated to modern day Django, the middleware is:

from threading import current_thread

_requests = {}

def get_request():
    return _requests[current_thread()]

class GlobalRequestMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        _requests[current_thread()] = request
        return self.get_response(request)

I need to import get_request() to access the _requests dict.

Atcrank
  • 439
  • 3
  • 11