1

The age-old question: How can I automatically save last_modifed_user in django models?

I found in several places this general process how to do it using thread local. I'm hesitant to simply implement it that way because I'm not entirely sure of the consequences it has and because all these posts are old.

Is using thread local still the "recommended" way of doing this in django 3? Or does django3 have a better options of doing it?

beginner_
  • 7,230
  • 18
  • 70
  • 127
  • Have you tried to see the django docs for this? – ParthS007 Apr 06 '20 at 09:30
  • Separation of concerns means the `request` isn't available in the model (and there are many cases when a model change isn't triggered by a request anyway, like a management command). So no, nothing has changed. – dirkgroten Apr 06 '20 at 10:00
  • The alternative to the method mentioned in the question you linked is: Implement it for user-facing views in the views or forms themselves (by creating a mixin that you inherit in all your views/forms); implement in your admin views (also with a mixin); and implement it in your management commands. Just not in the model. – dirkgroten Apr 06 '20 at 10:03

1 Answers1

1

No, this hasn't changed. Simply because separation of concern is an architectural principle of MVC (model-view-controller), which is also how Django (model-view-template) and most web frameworks with ORM are architected. Models know nothing about the request, it's not available (and in many cases there isn't a request at all when a model is saved, think of management commands or regular tasks running in the background).

The alternative to thread local is to make sure you implement it yourself in the controller layer (view layer in Django):

  • Create a view mixin that you can mix with all the generic views that use the ModelFormMixin to save the user into the model (ModelFormMixin.form_valid()). Or combine it with a form mixin where the user is passed to the form (FormMixin.get_form_kwargs()) and saved when the form is saved (ModelForm.save()).
  • Create a ModelAdmin mixin that does the same when saving a model in the django admin site.

This of course means someone on your team may forget to do it when creating new views and forms. The link you posted contains an answer as to the advantages and disadvantages of using thread local.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • Thanks. I was already looking into "doing it yourself" but was hitting roadblocks all over the place hence the question. So I decided to use the thread local version of doing it as it works regardless of form or extension used (i will have regular forms but also use django rest framework) – beginner_ Apr 07 '20 at 04:58