Cheknov
Cheknov

Reputation: 2082

How to know which values are different from the existing in the database given a request.POST

I have this view (truncated) to edit existing Projects:

def edit_project(request):
    if request.method == 'POST':
        project_to_edit = Project.objects.get(pk=request.POST['project_id'])
        form = CreateNewProjectForm(request.POST, instance=project_to_edit)
        if form.is_valid():
            form.save()
            return redirect('project_page')
        else:
            return redirect('edit_project')
    return redirect('index')

It works great, everything as expected but I would like to somehow know which fields are being updated/modified in the most pythonic way.

The reason I want to know which fields are modified is to save a record in my AuditHistory model for each modified field.

Ideally I would like to add the following code after the form.save() line:

username = None
if request.user.is_authenticated:
    user = request.user
if user:
    #for each modified field, save a row into AuditHistory
    audit_history_entry = AuditHistory(user=user, event="Edit Project", changed_field="?", old_value="?", new_value="?")
    audit_history_entry.save()

Upvotes: 0

Views: 44

Answers (1)

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

FieldTracker is what you need.

All you need to use is add this to your model:

tracker = FieldTracker()

You can track if field changed:

>>> a = Post.objects.create(title='First Post')
>>> a.title = 'Welcome'
>>> a.tracker.has_changed('title')
True
>>> a.tracker.has_changed('body')
False

Obtain all changed fields:

>>> a = Post.objects.create(title='First Post')
>>> a.title = 'Welcome'
>>> a.body = 'First post!'
>>> a.tracker.changed()
{'title': 'First Post', 'body': ''}

And see what was the previous value:

>>> a = Post.objects.create(title='First Post')
>>> a.title = 'Welcome'
>>> a.tracker.previous('title')
u'First Post'

FieldTracker requires django-model-utils which could be installed with pip:

pip install django-model-utils

Upvotes: 1

Related Questions