I\'ve been looking for a way to create a read-only form field and every article I\'ve found on the subject comes with a statement that \"this is a bad idea\". Now for an in
When using a disabled field, you also need to make sure it remains populated correctly if the form fails validation. Here's my method, which also takes care of malicious attempts to change the data submitted:
class MyForm(forms.Form):
MY_VALUE = 'SOMETHING'
myfield = forms.CharField(
initial=MY_VALUE,
widget=forms.TextInput(attrs={'disabled': 'disabled'})
def __init__(self, *args, **kwargs):
# If the form has been submitted, populate the disabled field
if 'data' in kwargs:
data = kwargs['data'].copy()
self.prefix = kwargs.get('prefix')
data[self.add_prefix('myfield')] = MY_VALUE
kwargs['data'] = data
super(MyForm, self).__init__(*args, **kwargs)