Skip to content

Instantly share code, notes, and snippets.

Embed
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():
try:
return _user.value
except AttributeError:
return None
"""
Register it as middleware.
"""
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'project.current_user.CurrentUserMiddleware',
]
"""
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
You can’t perform that action at this time.