2

I'm using the right code for inserting an ImageField in my html page but it still won't render the image, showing a broken link instead. This is the code:

<img src=" {{ model.imageFieldName.url }}>

I'm using 1.8 with debug=truee on my windows machine. I'm new to web development so any explanations would be appreciatied.

  • edit: forgot the trailing " – Shashwat Chetan Dec 29 '15 at 11:51
  • Possible duplicate of [Django - How can I display a photo saved in ImageField?](http://stackoverflow.com/questions/9830183/django-how-can-i-display-a-photo-saved-in-imagefield) – Sayse Dec 29 '15 at 11:55
  • Maybe you don't have MEDIA_URL or MEDIA_ROOT properly configured – fasouto Dec 29 '15 at 11:58
  • @fasouto MEDIA_URL and MEDIA_ROOT are configured. I followed all the steps in the documentation. When I upload files I can see them in the MEDIA_ROOT (a local folder) I specified yet when I try to access the same I get broken links. – Shashwat Chetan Dec 29 '15 at 12:00
  • @Sayse That question had the asker using the field incorrectly. I am using it correctly AFAIK but correct me if I'm wrong. – Shashwat Chetan Dec 29 '15 at 12:03
  • Do you have your urls.py properly configured? https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development – fasouto Dec 29 '15 at 12:08
  • @fasouto Oh wow totally missed that thanks! That solved the problem. – Shashwat Chetan Dec 29 '15 at 14:25

2 Answers2

0

You can convert your image to base64 string in core and put it into src like that:

Python:

import base64
encoded_string = base64.b64encode(your_image)

Django template:

<img src="data:image/png;base64, {{ encoded_string }}">
Omkommersind
  • 276
  • 5
  • 13
0
  1. For rendering images from DB you need to upload all images into static/your_app/ directory. You may check it for example on the URL: 127.0.0.1:8000/static/your_app_name/uploads/name_of_image.svg where you should see an image!
  2. In your template use this syntax: <src="/{{ object.image_field_name }}> Notice that slash ! Without it you don't see the image.
Yaaaaaaaaaaay
  • 476
  • 3
  • 9