Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

widgets.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. def render(self, name, value, attrs=None):
  18. """
  19. Render the ``input`` field based on the defined ``template_name``. The
  20. image URL is take from *value* and is provided to the template as
  21. ``image_url`` context variable relative to ``MEDIA_URL``. Further
  22. attributes for the ``input`` element are provide in ``input_attrs`` and
  23. contain parameters specified in *attrs* and *name*.
  24. If *value* contains no valid image URL an empty string will be provided
  25. in the context.
  26. """
  27. if value is None:
  28. value = ''
  29. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  30. if value != '':
  31. # Only add the 'value' attribute if a value is non-empty.
  32. final_attrs['value'] = force_unicode(self._format_value(value))
  33. image_url = final_attrs.get('value', '')
  34. if image_url:
  35. image_url = "%s/%s" % (settings.MEDIA_URL, image_url)
  36. return render_to_string(self.template_name, Context({
  37. 'input_attrs': flatatt(final_attrs),
  38. 'image_url': image_url,
  39. 'image_id': "%s-image" % final_attrs['id'],
  40. }))
  41. class WYSIWYGTextArea(forms.Textarea):
  42. def __init__(self, *args, **kwargs):
  43. kwargs.setdefault('attrs', {})
  44. kwargs['attrs'].setdefault('class', '')
  45. kwargs['attrs']['class'] += ' wysiwyg'
  46. super(WYSIWYGTextArea, self).__init__(*args, **kwargs)