无法在Django中加载静态文件

时间:2018-04-21 18:55:13

标签: python html django

我正在尝试将图像添加到非常基本的html模板中。我能够渲染html文件,但遗憾的是图像不会显示。

这是我的错误:

Not Found: /exapp/pic.jpg
[21/Apr/2018 18:43:49] "GET /exapp/pic.jpg HTTP/1.1" 404 2145

我注意到django正在寻找带有/exapp/pic.jpg路径的文件,所以我在静态目录中创建了一个名为exapp的文件夹,并将图像放在那里。仍然没有图像:(

文件结构如下:

    ─ db.sqlite3
├── exapp
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       └── __init__.cpython-35.pyc
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-35.pyc
│   │   ├── __init__.cpython-35.pyc
│   │   ├── models.cpython-35.pyc
│   │   ├── urls.cpython-35.pyc
│   │   └── views.cpython-35.pyc
│   ├── static
│   │   └── exapp
│   │       └── pic.jpg
│   ├── templates
│   │   └── index.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
└── mysite
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   ├── settings.cpython-35.pyc
    │   ├── urls.cpython-35.pyc
    │   └── wsgi.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py

以下是有问题的HTML文件:

    <html>
    <head> 
        <title> Hello world</title>
    </head>

    <body>
        Look it worked 
    {% load static %}
    <img src="pic.jpg" alt="Smiley face" height="200" width="420">
    </body>

</html>

以下是设置文件:

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__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'tie19%e+ri*g3#54b)axh&!8rentwx)xnsjbk&kx09(10le%7a'

# 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',
    'exapp',
]

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 = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

以下是我的观点和网址文件:

 ---------url.py in mysite folder------------
    from django.contrib import admin
    from django.urls import path, include

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('exapp/',include('exapp.urls')),
    ]
    -----------urls.py in exapp folder--------------
    from django.urls import path


    from . import views 

    urlpatterns = [
        path('', views.index, name='index'),
    ]

 ----------Views in exapp folder--------------------------
    from django.shortcuts import render

    # Create your views here.
    from django.http import HttpResponse


    def index(request):
        return render(request,'index.html')

因此,作为一个纲要,HTML模板会渲染到页面。但我出于某种原因无法弄清楚如何将html代码中链接的图像显示到屏幕上。一切似乎都在正确的地方。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您应该尝试更改图片来源。

这就是你所拥有的:

<img src="pic.jpg" alt="Smiley face" height="200" width="420">

试试这个:

<img src="{% static "exapp/pic.jpg" %}" alt="Smiley face" height="200" width="420">

这对我有用!

祝你好运!