Loading...

django: save one field of a formset at a time


My django app connects to a sql server database. On my template I have an editable datatable/formset. Whenever a user edits a field and hits enter, I want only the edited field to be saved. As far as I know AJAX is the only approach to do this, especially if you want the value of the edited field to be the only one transfered to the server. Let's put this case aside for now and accept transferring all data of the formset at once. Also, the formset is based on a sql server view that includes calculated values. Hence, executing formset.save() will raise an error. Instead I have to use the underlying table to save the modified value. What would be best practice to identify the changed field and save only this one?

Let's say the underlying table is costsperdiem that corresponds to a model in my django app and 'costs' is the name of the editable field I want to save then my approach is as follows:

  1. check if the formset is valid
  2. loop through the forms of the formset using changed_data to seek for the modified field
  3. using a model instance to filter for the modified record
  4. pass the modified value to the model
  5. save the model

which looks like this in code:

formset = FormSet_CostsPerDiem(request.POST)
    if formset.is_valid():
    for f in formset.forms:
        if 'costs' in f.changed_data:
            val2save=f.cleaned_data['costs']
            id=f.cleaned_data['id_costsperdiem']
            rec2save=costsperdiem.objects.filter(pk=id)
            rec2save.costs=val2save
            rec2save.save()

What is best practice to do something like this?

- - Source
comments powered by Disqus