Django read-only field

How to set read-only field in Django form? I know how to disable a field, but that is not what I am looking for. Any help would be greatly appreciated.

+7
python django forms django-forms readonly
source share
3 answers

When defining Field you can use the optional attrs parameter. To wit:

 somefield = forms.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'}) ) 
+9
source share

In django 1.9, in the available Field.disabled attribute: https://docs.djangoproject.com/en/1.9/ref/forms/fields/#disabled

A disabled boolean argument, when set to True, disables the form field using the disabled HTML attribute so that it is not editable by users. Even if the user discards the value of the fields sent to the server, it will be ignored in favor of the value from the original form data.

otherwise

use widget attribute 'readonly'

 class PatientForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientForm, self).__init__(*args, **kwargs) self.fields['field'].widget.attrs['readonly'] = True class Meta: model = Patient 
+5
source share

In Django 1.9+ :

 somefield = forms.CharField(disabled=True) 
+4
source share

All Articles