Last active
May 21, 2019 18:57
-
-
Save vinidmpereira/9206c41715fea66ae2886d2f573acd41 to your computer and use it in GitHub Desktop.
get_current_user middleware.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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