PageRenderTime 119ms CodeModel.GetById 44ms RepoModel.GetById 1ms app.codeStats 0ms

/readonlyfield.py

https://github.com/becomingGuru/djangoutils
Python | 43 lines | 41 code | 2 blank | 0 comment | 2 complexity | 7ee5d3a2030723a9fed92cc95e1279c8 MD5 | raw file
  1. from django.utils.html import escape
  2. from django.utils.safestring import mark_safe
  3. from django.forms.util import flatatt
  4. from django import forms
  5. class ReadOnlyWidget(forms.Widget):
  6. def render(self, name, value, attrs):
  7. final_attrs = self.build_attrs(attrs, name=name)
  8. if hasattr(self, 'initial'):
  9. value = self.initial
  10. return mark_safe("<p %s>%s</p>" % (flatatt(final_attrs), escape(value) or ''))
  11. def _has_changed(self, initial, data):
  12. return False
  13. class ReadOnlyField(forms.Field):
  14. widget = ReadOnlyWidget
  15. def __init__(self, widget=None, label=None, initial=None, help_text=None):
  16. super(type(self), self).__init__(self, label=label, initial=initial,
  17. help_text=help_text, widget=widget)
  18. self.widget.initial = initial
  19. def clean(self, value):
  20. return self.widget.initial
  21. class ReadOnlyWidget2(forms.Widget):
  22. def __init__(self, original_value, display_value):
  23. self.original_value = original_value
  24. self.display_value = display_value
  25. super(ReadOnlyWidget2, self).__init__()
  26. def _has_changed(self, initial, data):
  27. return False
  28. def render(self, name, value, attrs=None):
  29. if self.display_value is not None:
  30. return unicode(self.display_value)
  31. return unicode(self.original_value)
  32. def value_from_datadict(self, data, files, name):
  33. return self.original_value