pythondjangodjango-simple-history

django-simple-history track User from python shell


We are using django-simple-history to track changes in our models. All models have a history = HistoricalRecords() field. When making changes to a model from the python shell, the changes are tracked, however the changed_by field is saved as None. When changes are made in admin, the simple_history middleware grabs the User instance from whoever is logged in. Obviously in shell we don't have that. Is there any way to manually inject the User instance based on an existing Account object?

Unfortunately I'm not able to change any of these models, so I can't add any of the history user getters and setters to our models (project manager is very strict about refactoring and we also have a lot of models)


Solution

  • As shown in the docs, for a particular object with history called ObjectWithHistory, you can set the history user on the object before saving like this:

    o = ObjectWithHistory(*kwargs)
    o._history_user = this_user
    o.save()