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
I've just created the simplest possible widget for a readonly field - I don't really see why forms don't have this already:
class ReadOnlyWidget(widgets.Widget):
"""Some of these values are read only - just a bit of text..."""
def render(self, _, value, attrs=None):
return value
In the form:
my_read_only = CharField(widget=ReadOnlyWidget())
Very simple - and gets me just output. Handy in a formset with a bunch of read only values. Of course - you could also be a bit more clever and give it a div with the attrs so you can append classes to it.
For django 1.9+
You can use Fields disabled argument to make field disable.
e.g. In following code snippet from forms.py file , I have made employee_code field disabled
class EmployeeForm(forms.ModelForm):
employee_code = forms.CharField(disabled=True)
class Meta:
model = Employee
fields = ('employee_code', 'designation', 'salary')
Reference https://docs.djangoproject.com/en/dev/ref/forms/fields/#disabled