In a Django form, how do I make a field read-only (or disabled)?
When the form is being used to create a new entry, all fields should be enabled - but when the recor
Two more (similar) approaches with one generalized example:
1) first approach - removing field in save() method, e.g. (not tested ;) ):
def save(self, *args, **kwargs):
for fname in self.readonly_fields:
if fname in self.cleaned_data:
del self.cleaned_data[fname]
return super(, self).save(*args,**kwargs)
2) second approach - reset field to initial value in clean method:
def clean_(self):
return self.initial[] # or getattr(self.instance, fieldname)
Based on second approach I generalized it like this:
from functools import partial
class (...):
def __init__(self, ...):
...
super(, self).__init__(*args, **kwargs)
...
for i, (fname, field) in enumerate(self.fields.iteritems()):
if fname in self.readonly_fields:
field.widget.attrs['readonly'] = "readonly"
field.required = False
# set clean method to reset value back
clean_method_name = "clean_%s" % fname
assert clean_method_name not in dir(self)
setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))
def _clean_for_readonly_field(self, fname):
""" will reset value to initial - nothing will be changed
needs to be added dynamically - partial, see init_fields
"""
return self.initial[fname] # or getattr(self.instance, fieldname)