Login

Read-only Model Form Base Class

Author:
tgandor
Posted:
April 14, 2014
Language:
Python
Version:
1.4
Score:
1 (after 1 ratings)

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
from django import forms

class ReadOnlyForm(forms.ModelForm):
    """Base class for making a form readonly."""
    def __init__(self, *args, **kwargs):
        from django.utils.translation import ugettext as _
        from django.forms.widgets import Select
        super(ReadOnlyForm, self).__init__(*args, **kwargs)
        for f in self.fields:
            self.fields[f].label = _(self.fields[f].label)
            if isinstance(self.fields[f].widget, Select):
                self.fields[f].widget.attrs['disabled'] = 'disabled'
            else:
                self.fields[f].widget.attrs['readonly'] = 'readonly'

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

nqryn (on August 28, 2014):

Thanks, this is very useful. However, the readonly attribute does not work for inputs with type file, so I think that for files, there should be a new Widget, which displays the file.

#

Please login first before commenting.