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

widgets.py 1.8KB

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