Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
get_current_user middleware.
This should be a separate file, i usually install it on the maind django project folder.
from threading import local
from django.utils.deprecation import MiddlewareMixin
_user = local()
class CurrentUserMiddleware(MiddlewareMixin):
def process_request(self, request):
_user.value = request.user
def get_current_user():
return _user.value
except AttributeError:
return None
Register it as middleware.
Import it on your model and use it as a default.
from project.current_user import get_current_user
class SampleModel(models.Model):
field_1 = models.FloatField(verbose_name='field_1')
entry_time = models.DateTimeField(auto_now=False, auto_now_add=True)
created_by = models.ForeignKey('auth.User', null=True, default=get_current_user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment