VicenteC
VicenteC

Reputation: 422

"Could not load the image" from Django's media folder

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

Upvotes: 0

Views: 592

Answers (2)

bug
bug

Reputation: 4160

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.

Upvotes: 1

Engel
Engel

Reputation: 199

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/

Upvotes: 1

Related Questions