djangodjango-templatesdjango-settingsdjango-static

Django: Image from static folder doesn't load


I need help=)

Image from static folder doesn't load.

Version: Django 1.11.3

This is my code:

first_project/first_project/settings.py:

import os
 
 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
TEMPLATE_DIR=os.path.join(BASE_DIR,"templates")
STATIC_DIR=os.path.join(BASE_DIR,"static")
 
...
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first_app',
]
 
...
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
 
STATIC_URL = '/static/'
STATICFILES_DIRS=[
    STATIC_DIR,
    os.path.join(BASE_DIR,"first_app","static","first_app"),
]

first_project/templates/first_app/index.html:

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Yp</title>
</head>
<body>
<h1>This is yp picture!</h1>
<!--It works -->
<img src="/static/first_app/yp.jpg" alt="oh oh">
<!--It doesn't work-->
<img scr="{% static "first_app/yp.jpg" %}" alt="oh oh">
 
</body>
</html>

first_project/static/first_app/yp.jpg - the path to the image.

Thank you!


Solution

  • First of all, you wrote scr, not src and this should be corrected.

        <!--It doesn't work-->
    <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh">
    

    After that you may need to clear "first_app/" part from your code, because you are adressing your directory directly in settings file.