0

I'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.

models.py

class News(models.Model):
    news_id         = models.AutoField(primary_key=True, editable=False)
    news_img        = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )

urls.py

urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

MEDIA_ROOT  = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I've try to insert the path in the var in the following methods:

template.html

{% for news_f in news_f%}
<div>
  <img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}

and

{% for news_f in news_f%}
<div>
  <img src="{{news_f.news_img.url}}">
</div>
{% endblock %}

When I inspect the element in the browser, I get the correct path to the file.

<img src="/media/pictures/file.svg">

But it isn't displayed in the HTML:

Could not load the image
VicenteC
  • 311
  • 7
  • 26
  • I've tried this solution [2010 solution](https://stackoverflow.com/questions/2312714/can-the-django-dev-server-correctly-serve-svg) but nothing happens – VicenteC Oct 15 '19 at 23:52
  • Can you open and view the image in another tab? – aris Oct 16 '19 at 02:13

2 Answers2

1

That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.

Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/

Engel
  • 189
  • 3
  • 16
  • I've tried the same using .jpg and .png but nothing changes. – VicenteC Oct 15 '19 at 23:02
  • As long I remember in development it serves the files but in production it doesn't, is this your problem? – Engel Oct 16 '19 at 14:03
  • yes, I've tried adding .svg to MIME types but this was a solution for Django 1.x (2010). Is there another solution for Django 2x? – VicenteC Oct 16 '19 at 14:07
1

Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.

bug
  • 3,900
  • 1
  • 13
  • 24