How to correctly specify a static image in django

I have a template that displays an image:

{% load staticfiles %}

<img src="{% static "img/logo.png" %}" alt="My image"/>

The image link is broken, but it points to:

localhost/static/img/logo.png

What values ​​do I need to set for static_root, static_url and STATICFILES_DIRS in order to display this image correctly?

This is my directory structure:

myprojectname (top level)

--- myprojectname

--- --- myproectname

--- --- --- settings

--- --- --- --- base.py (setting.py)

--- --- static

--- --- --- img

This is my static configuration in settings:

STATIC_ROOT = '/Users/myuser/myprojectname/myprojectname'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    #normpath(join(SITE_ROOT, 'static')),
    os.path.join(BASE_DIR, "static"),
    '/Users/myuser/myprojectname/myprojectname/static',
)

Here is what he shows: enter image description here

I have already done the assembly and it does not work.

+4
source share
2 answers

Django. ...

STATIC_ROOT , production.

STATICFILES_DIRS , .

STATIC_ROOT STATICFILES_DIRS .

Django - . , css, JavaScript. Django . Django , .

DEBUG = True django.core.staticfiles INSTALLED_APPS, Django , STATICFILES_DIRS, STATIC_URL .

Nginx, Apache, CloudFront .. DEBUG = False, Django - .

:

$ python manage.py collectstatic

, STATICFILES_DIRS, STATIC_ROOT .

, , :

STATICFILES_DIRS. "static-assets". , "" .

STATIC_ROOT "" .

, 404 , :/static/img/logo.png, :/static/image/

, , , .

+10

"staticfiles" , settings.py

staticfiles .

  • CSS
  • JS

settings.py

STATIC_ROOT = os.path.join(PROJECT_DIR,'static')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
                os.path.join(PROJECT_DIR,'staticfiles'), # if your static files folder is named "staticfiles"
)
TEMPLATE_DIRS = (
                os.path.join(PROJECT_DIR,'template'), # if your static files folder is named "template"
)

base.html

<link rel="stylesheet" type="text/css" href="{% static 'css/demo.css' %}" /> 

<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>

, base.html

{% extends "base.html" %}
{% load static %}


<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>


<div id="yourID" class="yourClass">
    <img src="{% static "images/something.gif" %}" alt="something" >
</div>
+3

Source: https://habr.com/ru/post/1533804/


All Articles