Reputation: 23
I want to log all my database changes being done from the application and not only from the django-admin. how can i achieve that ? Currently we can only see the history in django admin for the changes done through the admin interface. do i need to define signals for this?
Upvotes: 0
Views: 4887
Reputation: 10382
Django admin uses LogEntry.objects.log_action
to record those history changes. There's nothing stopping you from calling that same method in your own code to record changes made elsewhere.
You can use a pre_save
signal to get the object before committing to the database and then fetch the old values from the database to compare and check for changes.
The formatting of the message can be a plain string, but the admin puts it in a JSON format so it can be translated. You can look at the source for construct_change_message
is django.contrib.admin.utils
to figure out that JSON format if you want to continue using that for the ManyToManyField
, etc.
Upvotes: 2
Reputation: 51
In settings.py, we have to enable logging. Put this code in your settings.py
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, }
Django documentation for logging - https://docs.djangoproject.com/en/1.11/topics/logging/#django-db-backends
Upvotes: 1
Reputation: 1000
There are two types of changes possible.
If you are concerned with the structural changes in the database, they are anyways saved in the migrations
folder inside your app directory.
If you want to log DB changes in terms of entries made in the database, you might find the python package django-audit-log
useful. You can install it via pip, and once installed, you can add trackers to your models by doing something like this:
from audit_log.models.managers import AuditLog
class YourModelName(models.Model):
#your model definition here
audit_log = AuditLog()
You can find the docs here
Another alternative is django-reversion which allows you to do version control for model instances.
Hope this helps!
Upvotes: 0