This is an extension to this SO question.
Is there an easy way to dynamically generate the required clean_X methods to ensure that read-only form fields do not get modified? I can manually write the methods as suggested by the linked question, but the novelty wears off very quickly when you have multiple forms with many fields that need to be made read-only.
There must be a better way!
Solution:
Based on the answer provided, I've decided to just override the Form.clean()
method in the base class. This is the class my forms inherit from which takes a parameter read_only
which is a list of instance attributes as strings.
class FormBase(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.read_only = kwargs.pop("read_only", [])
super(FormBase, self).__init__(*args, **kwargs)
#Disable any read only controls
for f in self.read_only:
self.fields[f].widget.attrs["readonly"] = True
def clean(self):
cleaned_data = super(FormBase, self).clean()
for f in self.read_only:
cleaned_data[f] = getattr(self.instance, f)
return cleaned_data