Below the Radar
Below the Radar

Reputation: 7635

Django - How to retrieve value of form fields before save?

What is the correct way to retrieve the value of a field before it is saved when the model form is submitted?

For instance, I am trying to get the field 'name' as it was before changed in the form. I was doing like below, and it works, but I am not sure that's the correct way to do it.

views.py:

if formset.is_valid():
  for form in formset:
    if form.has_changed and not form.empty_permitted:
       cd = form.cleaned_data
       new_fieldName = cd.get('name')
       old_fieldName = str(cd.get('id'))
       form.save()

Any suggestion?

Upvotes: 2

Views: 2509

Answers (2)

lanzz
lanzz

Reputation: 43168

formset.is_valid will call each form's is_valid method, which in turn will call full_clean, which calls _post_update, which updates the form's instance with the values submitted with the form. It would be too late to find references to the old values after you call formset.is_valid; you have two options:

  1. Store copies of the instance fields before you call formset.is_valid:

    saved = {}
    for form in formset.forms:
        saved[form.instance.pk] = form.instance.__dict__.copy()
        # or keep only specific fields
    
  2. Retrieve a fresh instance of the record before you call its save:

    original = form._meta.model.objects.get(pk=form.instance.pk)
    # compare original against form.instance and observe differences
    # save your form when you're ready:
    form.save()
    

Upvotes: 6

Rodrigo Gil
Rodrigo Gil

Reputation: 123

You have also pre_save(). I use is_valid to validate any errors or restrictions to the fields and pre_save to automate processes.

Hope it helps.

Upvotes: 1

Related Questions