2👍
Use class based views in your applications so you can use the full advantages of the cool Mixins
,
I usually create a Mixin
that can be added to any CreateView or UpdateView.
class withAudit(object):
"""
A mixin that will create an audit record wither the action is
Create or Update
"""
def get_success_url(self):
"""
This will be called when the form is valid and saved.
"""
# create the record
audit = Auditor(content_type= ContentType.objects.get_for_model(self.model))
audit.object_id = self.object.pk
audit.user = request.user
# You will need a way to capture this action.
# there are many ways to do it.
audit.action = "Create"
audit.save()
return super(withAudit, self).get_success_url()
In your views you have to use it this way
class CarCreate(withAudit, CreateView):
model = Car
For update
class CarUpdate(withAudit, UpdateView):
model = Car
You can do the following to any UpdateView or CreateView in your application. However, For Deleting the object, I think you will need another mixin which will capture the data before performing the action. You need to see the class based views docs in order to customise these as you want.
The same idea can be done with decorators if you really want keep using method based views.
If you have a big application with high traffic, this process should be done in the background where you define a stack or queue an you keep passing these information to it, which will provide a better performance indeed. Some big applications using another database for logs and audit.