Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model forms - disabled fields in changed_data

I have a form base class which checks if the instance the form is updating has changed, and does not save if it has not changed.

this is in my custom model form, I override save:

class MyModelForm(models.ModelForm):
    # .. more code here..
        def save(self, commit=True):
            if self.has_changed():
               # Won't do anything if the instance did not changed
               return self.instance
            return super(MyModelForm, self).save(commit)

A LOT of my forms use this base class. Now, one of my forms have a few fields which I set to disabled=True (django 1.9 +). So in one of my forms:

def __init__(self, *args, **kwargs):
      ## ..code
      self.fields['address'].disabled = True

After a lot of debugging why the form.has_changed() is True (hence the instance is saved for no reason), even when I save the form without changing the instance. I've found out that django includes disabled fields in changed_data - which makes no sense, as disabled fields should not be altered by the user anyway.

Am I missing something or it is a bug, or maybe that how it should work? How can I resolve this without too much changes, as the form base class is used a lot in my code.

like image 525
user3599803 Avatar asked Aug 31 '25 20:08

user3599803


1 Answers

This is a known issue with DjangoProject with the ticket at https://code.djangoproject.com/ticket/27431 and the corresponding PR at https://github.com/django/django/pull/7502. As this answer is being written the PR is merged with master so the latest version should have this fixed.

A workaround this is as follows

for form in formset:
    if form.has_changed() and form not in formset.deleted_forms:
        fields = form.changed_data
        up_f = [field for field in fields if not form.fields[field].disabled]
        if len(up_f) > 0:
            updated_data.append(form.cleaned_data)

This results in updated_data having the only forms that are updated and not deleted.

like image 191
pr4n Avatar answered Sep 04 '25 05:09

pr4n