I am writing a site on Django. There is such a problem: There is a Client model for almost everywhere on the site the user needs to display his clients. Initially, I wrote in each form as follows:

Client.objects.filter(user=request.user) 

Then he made his Manager with the method in which the user should be transferred, but in general this does not eliminate the problem of constantly transferring the user. How can I make the current user available in models.py?

    2 answers 2

    In general, this violates the logic of Django. There it is proposed to drag the Request object manually, and, yes, to do Client.objects.filter(user=request.user) . If this is done many times, you can in fact in the function to issue:

     # models.py ... def own_clients(request): return Client.objects.filter(user=request.user) ... 

    And, accordingly, use:

     # views.py from .models import ..., own_clients ... ... = own_clients(request).all() 

    On the other hand, in principle, make a copy of the request local to the stream:

     # middleware.py import threading _local_storage = threading.local() class CurrentRequestMiddleware(object): def process_request(self, request): _local_storage.request = request def get_current_request(): return getattr(_local_storage, "request", None) def get_current_user(): request = get_current_request() if request is None: return None return getattr(request, "user", None) 

    In settings.py add to MIDDLEWARE_CLASSES this CurrentRequestMiddleware and then use it as you do:

     # models.py from django.db import models from .middleware import get_current_user class OwnManager(models.Manager): def get_queryset(self): qs = super(OwnManager, self).get_queryset() return qs.filter(user=get_current_user()) class Client(models.Model): ... own_objects = OwnManager() 

    But all this will work until the internal structure of the framework changes, and no one gave a guarantee for each request to create a separate thread (although in fact this seems to be the case). For example, I would not vouch for the performance of this when used in conjunction with django-gevent.

      Show the Client model and "almost everywhere" this is where, on the front?

      If I understand you correctly, then why not do it?

       class Client(models.Model): user = models.ForeignKey('User', verbose_name="user", related_name="clients") ... 

      then on the front you get clients like this {{request.user.clients.all}}