9

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?

Zoli
  • 831
  • 1
  • 11
  • 27

2 Answers2

12

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 %}
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • It's working if there is an image but for new form instances it raises: ValueError at /onsite_api/get_sponsor_form/-1/ The 'image' attribute has no file associated with it. – Zoli Jan 05 '16 at 14:34
  • Of course, I thought you would expect that to happen. I edited my answer. – Shang Wang Jan 05 '16 at 14:36
2

Those attributes are inside formfield.value, so:

{{ sponsorform.image.value.url }}
{{ sponsorform.image.value.path }}
{{ sponsorform.image.value.href }}
juanifioren
  • 633
  • 5
  • 18