beginner_
beginner_

Reputation: 7622

Django: Last modified by and created by user automatic saving

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?

Upvotes: 1

Views: 1352

Answers (1)

dirkgroten
dirkgroten

Reputation: 20682

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.

Upvotes: 1

Related Questions