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?
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.
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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With