1

I am currently trying to figure out why I get a 404 Error (not found). I have uploaded the ImageField of my Model to the static file 'article_img'. But when I want to show the stored image on the html site, the resource cannot be found.

What is the reason for that?

from django.db import models
from django.utils.translation import gettext_lazy as _

class Article(models.Model):
    group = models.ForeignKey(Group, on_delete=models.SET_NULL, verbose_name=_('group'), null=True)
    name = models.CharField(_('name'), max_length=200)
    image = models.ImageField(_('image'), upload_to='./static/lagerverwaltung/article_img/', blank=True, null=True)
   <div id="article_img_div">
        {% load static %}
        {% if article.image %}
            <img class="article_img" type="image" src="{{ article.image.url }}" alt="{% static 'lagerverwaltung/article_img/none.jpg' %}">
        {% endif %}
    </div>
Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
ynynloxx
  • 11
  • 1
  • check in your console (F12) in the network tab. There should be an HTTP request for that image. Try that url by yourself, you'll probably understand what's wrong. – Loïc Jul 17 '19 at 12:34
  • if you don't, please add more information to your question like : what web server are you using ? django development server ? nginx ? other ? Can you show your django settings.py file (hiding the secret key) ? – Loïc Jul 17 '19 at 12:37

1 Answers1

1

Since you are using Django as your web framework, make sure your project is structured properly. Your static files should be stored in a folder called static; for example, an image file with Django should be stored in:

my_app/static/my_app/image.jpg

Django's documentation for file structure also specifies how to serve static images.

Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

Define STATIC_URL: STATIC_URL = '/static/'

In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.

{% load static %} <img src="{% static "my_app/example.jpg" %}" alt="My image">

Like another comment said, you can check the developer console for the HTTP request going to the image and you can likely find out more information specific to your problem there. (Ctrl + Shift + I in Chrome)