Created
December 11, 2014 14:15
-
-
Save ar45/0714313a80bba0d8ac0d to your computer and use it in GitHub Desktop.
Making some fields on a form read only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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