невозможно разрешить "{% static 'images / image_name.jpg'%} - PullRequest
1 голос
/ 27 июня 2019

Я новичок в django и не могу загрузить изображения с bootstrap. Я получаю ошибку

не удается разрешить "{% static 'images / image_name.jpg'%}

Я понимаю, что это не поиск пути. Обратите внимание, что index.html в products/templates и base.html в templates/. index.html расширяется base.html.

Скажите, пожалуйста, где я неправильно установил path? 1018 *

Это моя структура папок

folder structure

E:.
|   1.py
|   db.sqlite3
|   manage.py
+---products
|   |   admin.py
|   |    ...
|   +---migrations
|   +---templates
|   |       index.html
+---pyshop
|   |   settings.py
|   |   urls.py
|   |   wsgi.py
|   |   __init__.py
+---static
|   |   press-single.html
|   |   single.html
|   |
|   +---admin
|   |   +---css
|   |   +---fonts
|   |   +---img
|   |   \---js
|   +---css
|   |   |   aos.css
|   |   |   bootstrap-datepicker.css
|   |   |   ...
|   |   |   style.css
|   |   |
|   |   \---bootstrap
|   |           bootstrap-grid.css
|   |           bootstrap-reboot.css
|   |           bootstrap.css
|   |
|   +---fonts
|   |   +---flaticon
|   |   \---icomoon
|   +---images
|   |       ac-nc-67336.svg
|   |       ...
|   |       trimble-2.svg
|   +---js
|   |       aos.js
|   |       ...
|   |       typed.js
|   |
|   \---scss
|       |   style.scss
|       |   _site-base.scss
|       |   _site-blocks.scss
|       |   _site-navbar.scss
|       |
|       \---bootstrap
+---templates
|       base.html

index.html

<!DOCTYPE html>

{% extends 'base.html' %}
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Products</title>
</head>

<body>
{% block content %}

<div class="pb-5" style="position: relative; z-index: 8;">
    <div class="container">
        <div class="row" style="margin-top: -50px;">
            <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                <img src="../../templates/images/img_1.jpg" alt="Image" class="img-fluid mb-3">
                <h3 class="text-primary h4 mb-2">Business Analytics</h3>
                <p>Accusantium dignissimos voluptas rem consequatur ratione illo sit quasi.</p>
                <p><a href="#">Read more</a></p>
            </div>
            <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                <img src="{% static 'images/img_2.jpg ' %}" alt="Image" class="img-fluid mb-3">
                <h3 class="text-primary h4 mb-2">Investment Solutions</h3>
                <p>Praesentium magnam pariatur quae necessitatibus eligendi voluptate ducimus.</p>
                <p><a href="#">Read more</a></p>
            </div>
            <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                <img src="{% static 'images/img_3.jpg ' %}" alt="Image" class="img-fluid mb-3">
                <h3 class="text-primary h4 mb-2">Individual Approach</h3>
                <p>Accusantium dignissimos voluptas rem consequatur ratione illo sit quasi.</p>
                <p><a href="#">Read more</a></p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

</body>
</html>

base.html

<!doctype html>
{% load static %}
<html lang="en">
<head>
    <title>Inves &mdash; Colorlib Website Template</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css?family=Nunito:300,400,700" rel="stylesheet">

    <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css ' %}">

    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css ' %}">
    <link rel="stylesheet" href="{% static 'css/magnific-popup.css ' %}">
    <link rel="stylesheet" href="{% static 'css/jquery-ui.css ' %}">
    <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css ' %}">
    <link rel="stylesheet" href="{% static 'css/owl.theme.default.min.css ' %}">

    <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.css ' %}">

    <link rel="stylesheet" href="{% static 'fonts/flaticon/font/flaticon.css ' %}">

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

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

</head>
<body data-spy="scroll" data-target=".site-navbar-target" data-offset="300">
{% block content %}


{% endblock %}
<script src="{% static 'js/jquery-3.3.1.min.js ' %}"></script>
<script src="{% static 'js/jquery-ui.js ' %}"></script>
<script src="{% static 'js/popper.min.js ' %}"></script>
<script src="{% static 'js/bootstrap.min.js ' %}"></script>
<script src="{% static 'js/owl.carousel.min.js ' %}"></script>
<script src="{% static 'js/jquery.magnific-popup.min.js ' %}"></script>
<script src="{% static 'js/jquery.sticky.js ' %}"></script>
<script src="{% static 'js/jquery.waypoints.min.js ' %}"></script>
<script src="{% static 'js/jquery.animateNumber.min.js ' %}"></script>
<script src="{% static 'js/aos.js ' %}"></script>

<script src="{% static 'js/main.js ' %}"></script>

</body>

</html>

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products.apps.ProductsConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'pyshop.urls'

TEMPLATES = [
    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'pyshop.wsgi.application'


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

views.py

from django.http import HttpResponse
from django.shortcuts import render
from .models import Product


# Create your views here.

def index(request):
    products = Product.objects.all()
    return render(request, 'index.html', {'products': products})


# request object, html template, dictionary to import from db

def index2(request2):
    return HttpResponse('new page')

view page source

    <!DOCTYPE html>

        <!doctype html>

    <html lang="en">
    <head>
        <title>Inves &mdash; Colorlib Website Template</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link href="https://fonts.googleapis.com/css?family=Nunito:300,400,700" rel="stylesheet">

        <link rel="stylesheet" href="/static/fonts/icomoon/style.css">

        <link rel="stylesheet" href="/static/css/bootstrap.min.css">
        <link rel="stylesheet" href="/static/css/magnific-popup.css">
        <link rel="stylesheet" href="/static/css/jquery-ui.css">
        <link rel="stylesheet" href="/static/css/owl.carousel.min.css">
        <link rel="stylesheet" href="/static/css/owl.theme.default.min.css">

        <link rel="stylesheet" href="/static/css/bootstrap-datepicker.css">

        <link rel="stylesheet" href="/static/fonts/flaticon/font/flaticon.css">

        <link rel="stylesheet" href="/static/css/aos.css">

        <link rel="stylesheet" href="/static/css/style.css">

    </head>
    <body data-spy="scroll" data-target=".site-navbar-target" data-offset="300">


    <div class="pb-5" style="position: relative; z-index: 8;">
        <div class="container">
            <div class="row" style="margin-top: -50px;">
                <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                    <img src="../../templates/images/img_1.jpg" alt="Image" class="img-fluid mb-3">
                    <h3 class="text-primary h4 mb-2">Business Analytics</h3>
                    <p>Accusantium dignissimos voluptas rem consequatur ratione illo sit quasi.</p>
                    <p><a href="#">Read more</a></p>
                </div>
                <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                    <img src="/static/images/img_2.jpg" alt="Image" class="img-fluid mb-3">
                    <h3 class="text-primary h4 mb-2">Investment Solutions</h3>
                    <p>Praesentium magnam pariatur quae necessitatibus eligendi voluptate ducimus.</p>
                    <p><a href="#">Read more</a></p>
                </div>
                <div class="col-md-6 col-lg-4 mb-4 mb-lg-0">
                    <img src="/static/images/img_3.jpg" alt="Image" class="img-fluid mb-3">
                    <h3 class="text-primary h4 mb-2">Individual Approach</h3>
                    <p>Accusantium dignissimos voluptas rem consequatur ratione illo sit quasi.</p>
                    <p><a href="#">Read more</a></p>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/js/jquery-3.3.1.min.js"></script>
    <script src="/static/js/jquery-ui.js"></script>
    <script src="/static/js/popper.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/owl.carousel.min.js"></script>
    <script src="/static/js/jquery.magnific-popup.min.js"></script>
    <script src="/static/js/jquery.sticky.js"></script>
    <script src="/static/js/jquery.waypoints.min.js"></script>
    <script src="/static/js/jquery.animateNumber.min.js"></script>
    <script src="/static/js/aos.js"></script>

    <script src="/static/js/main.js"></script>

    </body>

    </html>

enter image description here

actual webpage

actual webpage

Редактировать: добавление этого к settings.py сработало

STATIC_URL = '/static/'

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),

]

Ответы [ 4 ]

1 голос
/ 27 июня 2019

Существует два сценария: один для статических файлов, другой для медиа-файлов. для статических файлов, таких как ваши css, js, sass и другие, вам необходимо создать статический каталог, а для изображений и видео вам потребуется создать каталог мультимедиа. Здесь при локальной разработке вам необходимо создать две папки: одну, в которую будут извлекаться статические файлы, и одну, из которой будут извлекаться статические файлы. при работе внешние службы, такие как AWS, используются для безопасной загрузки статических или мультимедийных файлов.

python manage.py collectstatic

работает как сбор статических файлов с другого сервера, который настроен на статический URL. надеюсь, ты понял суть. для настройки ваших статических файлов посмотрите это видео . что прекрасно объясняет, как это сделать легко. также, STATICFILES_DIRS = [ BASE_DIR("static"), ] and got the error ` BASE_DIR("static"), TypeError: 'str' object is not callable Здесь BASE_DIR - объект, содержащий каталог, который имеет строковый тип. Когда вы делаете это BASE_DIR («статический»), он пытается вызвать его как функцию с параметром. вот почему объект не вызывается ошибкой. для всех ваших статических файлов связанных запросов в django смотрите видео.

1 голос
/ 27 июня 2019

<img src="% static 'images/img_2.jpg ' %}"

  1. здесь отсутствует открывающая фигурная скобка
  2. и после имени файла (перед закрывающей одинарной кавычкой) появляется ненужный пробел, что приводит к излишку %20в сгенерированном статическом файле URL
  3. Вы не настроили STATIC_ROOT

Обратите внимание, вы должны удалить папку destination (os.path.join(BASE_DIR, "static")) для collectstatic из STATICFILES_DIRS, который является списком (дополнительных) исходных папок для collectstatic.Ваш текущий конфиг не будет работать на продукт.

1 голос
/ 27 июня 2019

В settings.py добавить:

# Where default server looks for static files
STATICFILES_DIRS = [
    ROOT_DIR("static"),
]

Также вы можете попробовать: ./manage.py collectstatic

Редактировать:

Отсюда ROOT_DIR:

import environ

ROOT_DIR = environ.Path(__file__) - 3  # (/a/b/myfile.py - 3 = /)
APPS_DIR = ROOT_DIR('server/apps')
0 голосов
/ 27 июня 2019

Поместите эту строку в конце settings.py.

STATICFILES_DIRS = [
    STATIC_ROOT,
]

После этого вы можете получить доступ к файлам в этом каталоге в Django. Надеюсь, это помогло!

...