I started thinking about whether the login user could be stored in the model user_created (creator) and user_updated (updater) by common processing.
Until then, I wrote the process of passing user information from view to form and storing it in user_created and user_updated.
From Official
Middleware is a framework for adding hooks to Django's request / response processing.
You can define the processing to be performed when sending a request or before returning a response.
common/middlewares/threadlocals.py
from threading import local
THREAD_LOCAL = local()
def set_thread_variable(key, value):
"""Store values in thread-local data
"""
setattr(THREAD_LOCAL, key, value)
def get_thread_variable(key, default=None):
"""Get values from thread-local data
"""
return getattr(THREAD_LOCAL, key, default)
def get_request():
"""Get request information from thread local data
"""
return get_thread_variable('request')
common/middlewares/request_store_middleware.py
from common.middlewares.threadlocals import set_thread_variable
from django.utils.deprecation import MiddlewareMixin
class RequestStoreMiddleware(MiddlewareMixin):
def process_request(self, reuqest):
set_thread_variable('request', reuqest)
Since we want request information this time, we will define only process_request
.
settings.py
.
..
...
MIDDLEWARE = [
.
..
...
'common.middlewares.request_store_middleware.RequestStoreMiddleware', #add to
]
...
..
.
I decided to use it in models.py because the purpose is to store user information when saving to DB.
common/models.py
.
..
...
from common.middlewares.threadlocals import get_request
from django.db.models.signals import pre_save
...
..
.
class Company(BaseModel):
"""Corporate model class
"""
...
..
.
created_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)
updated_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True)
...
..
.
def set_user_receiver(sender, instance, *args, **kwargs)
request = get_request() #Authentication check may be done before storing user information
instance.created_user = request.user
instance.updated_user = request.user
pre_save.connect(set_user_receiver, sender=Company) # pre_If you use save, save()You can register the function you want to call before execution.
end
Recommended Posts