Read-only Model Form Base Class

The simplest way of displaying a "details" table about any model, is to show a ModelFrom with all fields readonly or (selects) disabled.

Also, the labels are preferably translatable, not just capitalized names of the column tables in your models. So the constructor translates the field labels as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

fromdjangoimportformsclassReadOnlyForm(forms.ModelForm):"""Base class for making a form readonly."""def__init__(self,*args,**kwargs):fromdjango.utils.translationimportugettextas_fromdjango.forms.widgetsimportSelectsuper(ReadOnlyForm,self).__init__(*args,**kwargs)forfinself.fields:self.fields[f].label=_(self.fields[f].label)ifisinstance(self.fields[f].widget,Select):self.fields[f].widget.attrs['disabled']='disabled'else:self.fields[f].widget.attrs['readonly']='readonly'