Skip to content
This repository has been archived by the owner on Dec 28, 2017. It is now read-only.

Add a widget for form based preview #18

Open
Syerram opened this issue Feb 24, 2013 · 0 comments
Open

Add a widget for form based preview #18

Syerram opened this issue Feb 24, 2013 · 0 comments

Comments

@Syerram
Copy link

Syerram commented Feb 24, 2013

Sometimes you have to show a form as is [eg. crispy forms etc], where you won't have a chance to use the thumbnail tags to show the desired thumbnails.
e.g.

form.as_p <!-- we could access the instance inside a form but it gets ugly soon -->

In such cases, I recommend at its simplest form, use a widget.

#the form field. pass the thumbnail name you would want to use
photo = forms.ImageField(required=False, widget=ImagePreviewWidget(attrs={'thumb':'50x50_cropped'}))

#the widget
class ImagePreviewWidget(widgets.FileInput):
    """
    Widget that renders html img so it can be previewed along side upload input.
    Just rendering the upload input shows the link but not the image
    """
    def __init__(self, attrs={}):
        super(UrlToImageWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        input_file = super(UrlToImageWidget, self).render(name, value, attrs)
        output = []
        if isinstance(value, ImageWithThumbsFieldFile):
            url = value.generate_url(self.attrs.get('thumb', ''))
            output = [u"<img src={url} class={img_class} />".format(url=url, img_class='img_preview')]

        return mark_safe(u'\n'.join(output)) + input_file

We can get fancy on passing thumb names inside of the template by overriding form rendering, but this at least gets my preview next the input.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant