PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/enhydris/hcore/widgets.py

https://bitbucket.org/indifex/hydroscope
Python | 59 lines | 50 code | 2 blank | 7 comment | 0 complexity | c78e4cf39dd7d34449f4916684a1f066 MD5 | raw file
  1. """
  2. Hcore Widgets
  3. """
  4. from django.utils.html import escape
  5. from django.utils.safestring import mark_safe
  6. from django.forms.util import flatatt
  7. from django.template.loader import render_to_string
  8. import django.forms as forms
  9. class SelectWithPop(forms.Select):
  10. """
  11. This widget creates a popup with a plus button on the right which
  12. opens a form for inline instance creation of foreign models
  13. """
  14. def __init__(self, model_name='', *args, **kwargs):
  15. """
  16. Overiden init method to populate gentities
  17. """
  18. self.model_name = model_name
  19. super(SelectWithPop, self).__init__(*args, **kwargs)
  20. def render(self, name, *args, **kwargs):
  21. if not self.model_name:
  22. self.model_name = name
  23. html = super(SelectWithPop, self).render(name, *args, **kwargs)
  24. popupplus = render_to_string("hcore/form/popplus.html",
  25. {'field': self.model_name,
  26. 'orig_name': name})
  27. return html+popupplus
  28. class ReadOnlyWidget(forms.Widget):
  29. """
  30. This is a widget for read only form fields.
  31. """
  32. def render(self, name, value, attrs):
  33. final_attrs = self.build_attrs(attrs, name=name)
  34. if hasattr(self, 'initial'):
  35. value = self.initial
  36. return mark_safe("<p %s>%s</p>" % (flatatt(final_attrs),
  37. escape(value) or ''))
  38. def _has_changed(self, initial, data):
  39. return False
  40. class ReadOnlyField(forms.Field):
  41. """
  42. This is a formfield similar to editable=False but actually displays the
  43. value of the field.
  44. """
  45. widget = ReadOnlyWidget
  46. def __init__(self, widget=None, label=None, initial=None, help_text=None):
  47. super(type(self), self).__init__(self, label=label, initial=initial,
  48. help_text=help_text, widget=widget)
  49. self.widget.initial = initial
  50. def clean(self, value):
  51. return self.widget.initial