Skip to content

Instantly share code, notes, and snippets.

@ar45
Created December 11, 2014 14:15
Show Gist options
  • Save ar45/0714313a80bba0d8ac0d to your computer and use it in GitHub Desktop.
Save ar45/0714313a80bba0d8ac0d to your computer and use it in GitHub Desktop.
Making some fields on a form read only
from django import forms
from readonly_form import ReadOnly
class MyForm(ReadOnly):
"""
This form may now add fields as readonly
"""
class Meta:
model = auth.User
exclude = ('password', )
readonly = ('modified_by', 'last_login')
from django.utils.encoding import force_text
import types
def render(self, name, value, attrs=None):
attrs['disabled'] = 'disabled'
return super(self.__class__, self).render(name, value, attrs)
def value_from_datadict(self, data, files, name):
return self.original_value
def disable_widget(field):
widget = field.widget
widget.render = types.MethodType(render, widget)
widget.value_from_datadict = types.MethodType(value_from_datadict, widget)
return widget
class Readonly(object):
"""Base class for ReadonlyForm and ReadonlyModelForm which provides
the meat of the features described in the docstings for those classes.
"""
def __init__(self, *args, **kwargs):
super(Readonly, self).__init__(*args, **kwargs)
readonly = getattr(self.Meta, 'readonly', tuple())
if not readonly:
return
for name in readonly:
field = self.fields[name]
disable_widget(field)
field.widget.original_value = force_text(field.widget._format_value(getattr(self.instance, name)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment