django-orchestra-test/orchestra/forms/widgets.py

66 lines
2.1 KiB
Python
Raw Normal View History

import re
2014-05-08 16:59:35 +00:00
from django import forms
from django.utils.safestring import mark_safe
2014-07-08 15:19:15 +00:00
from django.utils.encoding import force_text
class ShowTextWidget(forms.Widget):
2014-07-09 16:17:43 +00:00
def __init__(self, *args, **kwargs):
for kwarg in ['bold', 'warning', 'hidden']:
setattr(self, kwarg, kwargs.pop(kwarg, False))
super(ShowTextWidget, self).__init__(*args, **kwargs)
2014-07-08 15:19:15 +00:00
def render(self, name, value, attrs):
value = force_text(value)
if value is None:
return ''
if hasattr(self, 'initial'):
value = self.initial
if self.bold:
final_value = u'<b>%s</b>' % (value)
else:
final_value = '<br/>'.join(value.split('\n'))
if self.warning:
final_value = (
u'<ul class="messagelist"><li class="warning">%s</li></ul>'
% final_value)
2014-07-08 15:19:15 +00:00
if self.hidden:
final_value = (
u'%s<input type="hidden" name="%s" value="%s"/>'
% (final_value, name, value))
2014-07-08 15:19:15 +00:00
return mark_safe(final_value)
2014-07-09 16:17:43 +00:00
2014-07-08 15:19:15 +00:00
def _has_changed(self, initial, data):
return False
2014-05-08 16:59:35 +00:00
class ReadOnlyWidget(forms.Widget):
def __init__(self, *args):
if len(args) == 1:
args = (args[0], args[0])
self.original_value = args[0]
self.display_value = args[1]
super(ReadOnlyWidget, self).__init__()
def render(self, name, value, attrs=None):
if self.display_value is not None:
return mark_safe(self.display_value)
return mark_safe(self.original_value)
def value_from_datadict(self, data, files, name):
return self.original_value
def paddingCheckboxSelectMultiple(padding):
""" Ugly hack to render this widget nicely on Django admin """
widget = forms.CheckboxSelectMultiple()
old_render = widget.render
def render(self, *args, **kwargs):
value = old_render(self, *args, **kwargs)
value = re.sub(r'^<ul id=(.*)>',
r'<ul id=\1 style="padding-left:%ipx">' % padding, value, 1)
return mark_safe(value)
widget.render = render
return widget