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
One simple option is to just type form.instance.fieldName
in the template instead of form.fieldName
.
awalker's answer helped me a lot!
I've changed his example to work with Django 1.3, using get_readonly_fields.
Usually you should declare something like this in app/admin.py
:
class ItemAdmin(admin.ModelAdmin):
...
readonly_fields = ('url',)
I've adapted in this way:
# In the admin.py file
class ItemAdmin(admin.ModelAdmin):
...
def get_readonly_fields(self, request, obj=None):
if obj:
return ['url']
else:
return []
And it works fine. Now if you add an Item, the url
field is read-write, but on change it becomes read-only.
Is this the simplest way?
Right in a view code something like this:
def resume_edit(request, r_id):
.....
r = Resume.get.object(pk=r_id)
resume = ResumeModelForm(instance=r)
.....
resume.fields['email'].widget.attrs['readonly'] = True
.....
return render(request, 'resumes/resume.html', context)
It works fine!
You can elegantly add readonly in the widget:
class SurveyModaForm(forms.ModelForm):
class Meta:
model = Survey
fields = ['question_no']
widgets = {
'question_no':forms.NumberInput(attrs={'class':'form-control','readonly':True}),
}
Setting readonly
on a widget only makes the input in the browser read-only. Adding a clean_sku
which returns instance.sku
ensures the field value will not change on form level.
def clean_sku(self):
if self.instance:
return self.instance.sku
else:
return self.fields['sku']
This way you can use model's (unmodified save) and avoid getting the field required error.
I think your best option would just be to include the readonly attribute in your template rendered in a <span>
or <p>
rather than include it in the form if it's readonly.
Forms are for collecting data, not displaying it. That being said, the options to display in a readonly
widget and scrub POST data are fine solutions.