I try to make sure that when creating a record in the table, the current user is saved. There is a class

class SourceHistory(models.Model): source = models.ForeignKey(Source, verbose_name=u'Источник', null=False, blank=False) editor = models.ForeignKey(User, verbose_name=u'Пользователь', null=True, blank=True) 

Which in admin.py looks like this

 @admin.register(SourceHistory) class SourceHistoryAdmin(admin.ModelAdmin): list_display = ('source', 'editor') def save_model(self, request, obj, form, change): obj.editor = request.user obj.save() 

Creating an object happens using the post_save signal.

 @receiver(post_save, sender=Source) def source_save_history(sender, **kwargs): source = kwargs.get('instance') for f in source.memorized_fields: if source.__getattribute__(f) != source.memorized_fields[f]: sh = SourceHistory.objects.create( source=source ) 

Accordingly, now when creating an object, the editor field remains empty. Question: how to create a SourceHistory object so that the user is saved?

    1 answer 1

    The current user is available only from a request that cannot be accessed from the model's functional.

    In the folder next to settings.py add the file middlewares.py with the following contents:

     try: from threading import local except ImportError: from django.utils._threading_local import local _thread_locals = local() def get_current_request(): return getattr(_thread_locals, 'request', None) def get_current_user(): request = get_current_request() if request: return getattr(request, 'user', None) class ThreadLocalMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): _thread_locals.request = request return self.get_response(request) 

    In settings.py , MIDDLEWARE add the list to the MIDDLEWARE list at the end:

    'название_проекта.middlewares.ThreadLocalMiddleware'

    In the file with the receiver add import:

    from название_проекта.middlewares import get_current_user

    The receiver itself will now look like this:

     @receiver(post_save, sender=Source) def source_save_history(sender, **kwargs): source = kwargs.get('instance') for f in source.memorized_fields: if source.__getattribute__(f) != source.memorized_fields[f]: sh = SourceHistory.objects.create( source=source, editor=get_current_user() ) 
    • Thank you very much! - Shelari