widgets.py 1.5 KB

123456789101112131415161718192021222324252627282930313233
  1. from django.utils.html import conditional_escape
  2. from django.utils.safestring import mark_safe
  3. from django.forms.widgets import ClearableFileInput, CheckboxInput
  4. from easy_thumbnails.files import get_thumbnailer
  5. from django.templatetags.static import static
  6. from django.utils.encoding import force_unicode
  7. class ImagePreviewFileInput(ClearableFileInput):
  8. def render(self, name, value, attrs=None,):
  9. substitutions = {
  10. 'clear_checkbox_label': self.clear_checkbox_label,
  11. 'initial' : '<img class="img-responsive img-thumbnail" width="%s" src="%s">' % (
  12. force_unicode('100%'),
  13. force_unicode(get_thumbnailer(value)['medium'].url if value and hasattr(value, 'url') else static('images/placeholder.svg'))
  14. )
  15. }
  16. template = '%(initial)s%(input)s'
  17. substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
  18. if not self.is_required:
  19. template = '%(initial)s%(clear_template)s%(input)s'
  20. checkbox_name = self.clear_checkbox_name(name)
  21. checkbox_id = self.clear_checkbox_id(checkbox_name)
  22. substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
  23. substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
  24. substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
  25. substitutions['clear_template'] = self.template_with_clear % substitutions
  26. return mark_safe(template % substitutions)