0

I'm trying to build a custom Image Widget in the following manner:

class ImageWidget(forms.widgets.Widget):

    template_name = 'widgets/picture.html'

    def get_context(self, name, value, attrs=None):

        return {'widget': {
            'name': name,
            'value': value,
        }}

    def render(self, name, value, attrs=None):
        context = self.get_context(name, value, attrs)
        template = loader.get_template(self.template_name).render(context)
        return mark_safe(template)

The problem is that value contains the file's relative path without including the MEDIA prefix (as a form field would). I don't know how to append or how to access that field in Django 1.8

Here's the picture.html file contents just in case:

Currently: <img src={{ widget.value }}>
<br>Change: <input id="id_profile_image" name="profile_image" type="file">

Rendered HTML:

<p>
  <label for="id_profile_image">Profile image:</label> Currently: <img src="profile_images/CSC_00111.jpeg">
  <br>Change: <input id="id_profile_image" name="profile_image" type="file">
</p>

I need the src attribute value to be /media/profile_images/CSC_00111.jpeg.

martincho
  • 4,517
  • 7
  • 32
  • 42

1 Answers1

0

You can add media manually like this

def get_context(self, name, value, attrs=None):

        return {'widget': {
            'name': name,
            'value': '/media/' + value,
        }}
Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43