You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

widgets.py 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from django.conf import settings
  2. from django import forms
  3. from django.template import Context
  4. from django.forms.widgets import FileInput
  5. from django.utils.encoding import force_unicode
  6. from django.template.loader import render_to_string
  7. from django.forms.util import flatatt
  8. class ImageInput(FileInput):
  9. """
  10. Widget prodiving a input element for file uploads based on the
  11. Django ``FileInput`` element. It hides the actual browser-specific
  12. input element and shows the available image for images that have
  13. been previously uploaded. Selecting the image will open the file
  14. dialog and allow for selecting a new or replacing image file.
  15. """
  16. template_name = 'partials/image_input_widget.html'
  17. attrs = {'accept': 'image/*'}
  18. def render(self, name, value, attrs=None):
  19. """
  20. Render the ``input`` field based on the defined ``template_name``. The
  21. image URL is take from *value* and is provided to the template as
  22. ``image_url`` context variable relative to ``MEDIA_URL``. Further
  23. attributes for the ``input`` element are provide in ``input_attrs`` and
  24. contain parameters specified in *attrs* and *name*.
  25. If *value* contains no valid image URL an empty string will be provided
  26. in the context.
  27. """
  28. if value is None:
  29. value = ''
  30. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  31. if value != '':
  32. # Only add the 'value' attribute if a value is non-empty.
  33. final_attrs['value'] = force_unicode(self._format_value(value))
  34. image_url = final_attrs.get('value', '')
  35. if image_url:
  36. image_url = "%s/%s" % (settings.MEDIA_URL, image_url)
  37. return render_to_string(self.template_name, Context({
  38. 'input_attrs': flatatt(final_attrs),
  39. 'image_url': image_url,
  40. 'image_id': "%s-image" % final_attrs['id'],
  41. }))
  42. class WYSIWYGTextArea(forms.Textarea):
  43. def __init__(self, *args, **kwargs):
  44. kwargs.setdefault('attrs', {})
  45. kwargs['attrs'].setdefault('class', '')
  46. kwargs['attrs']['class'] += ' wysiwyg'
  47. super(WYSIWYGTextArea, self).__init__(*args, **kwargs)