Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Log entry for an action by a user in a Django App

I need to create a log entry for changes made by a user to the database via the views in my django application.

I have enabled the django-admin module and I can retrieve the logs of the changes made using the admin interface like this:

from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType  recentActions = LogEntry.objects.all()  for each in recentActions:     print 'Action:', each.action_flag.__str__()     print 'Message:', each.object_repr     print 'Table:', ContentType.objects.get(id = each.content_type_id).name 

I want to create similar log entries for actions done by other users using the views in my django application. How do I do this ?

like image 888
unni Avatar asked Oct 26 '11 15:10

unni


People also ask

How does Django track user activity?

Enter the username and password of the superuser you just created with the manage.py command to log in. Next, you will see the Django admin dashboard. The "User visit log" has already been added to the Admin. Click on the "User visits" link.

How do I enable logs in Django?

By default, the LOGGING setting is merged with Django's default logging configuration using the following scheme. If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the dictConfig default if the key is missing) then all loggers from the default configuration will be disabled.

What is log entry in Django?

Whenever a user adds, deletes, or even changes an object in Django admin that action is recorded using a model called LogEntry in a table in the database called django_admin_log.


1 Answers

You're very close. You just need to create new LogEntry objects and save them. LogEntry has a shortcut function on objects to do this.

from django.contrib.admin.models import LogEntry, ADDITION, CHANGE  LogEntry.objects.log_action(             user_id=request.user.id,             content_type_id=ContentType.objects.get_for_model(model_object).pk,             object_id=object.id,             object_repr=unicode(object.title),             action_flag=ADDITION if create else CHANGE) 
like image 60
Andrew Wilkinson Avatar answered Oct 11 '22 10:10

Andrew Wilkinson