Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image url from django form

I have dificulties to get the image url out of django form.

Model:

class Sponsor(models.Model):
    image = ProcessedImageField(upload_to='sponsors/', 
                                processors=[SmartResize(300, 120, upscale=False)],
                                format='JPEG', 
                                options={'quality': 100}, 
                                null=True)

Form:

class SponsorForm(forms.ModelForm):

    class Meta:
        model = Sponsor
        fields = ('image',)

When I render it using:

{{ sponsorform.image }}

It prints:

Currently: <a href="/media/sponsors/random1.jpg">sponsors/random1.jpg</a> <br>Change: <input id="id_sponsor-image" name="sponsor-image" type="file">

So my question is, how to get that url in templates? I've tried:

{{ sponsorform.image.url }}
{{ sponsorform.image.path }}
{{ sponsorform.image.href }}

But nothing seems to work, any suggestions?

like image 330
Zoli Avatar asked Jan 05 '16 14:01

Zoli


People also ask

How does Django save Images?

We can now proceed and define a model that shall be used to store the images in our app. In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory.

Where to put Images in Django project?

Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image.


1 Answers

You should try {{ sponsorform.instance.image.url }}. In case the form is unbounded, you can just do:

{% if sponsorform.instance.image %}
    {{ sponsorform.instance.image.url }}
{% endif %}
like image 98
Shang Wang Avatar answered Sep 22 '22 15:09

Shang Wang