静态文件在 Django 开发中不起作用

Static files not working in Django development

我正在尝试遵循 Django 文档中名为 Managing static files 的部分。我有兴趣了解:

  1. 我做错了什么。
  2. 或者,Django 文档有什么问题。

1) 确保 django.contrib.staticfiles 包含在您的 INSTALLED_APPS 中。

在默认 settings.py 文件中:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',  #<****HERE*****
)

2) 在你的设置文件中,定义STATIC_URL,例如:STATIC_URL = '/static/'

在默认的settings.py:

STATIC_URL = '/static/'

3) 在您的模板中,要么硬编码 url,例如 /static/my_app/myexample.jpg

在mysite2/mysite2/views.py:

from django.http import HttpResponse

def index(request):
    return HttpResponse('''

        <h2>Hello</h2>
        <img src="/static/mysite2/Aerial03.jpg">


    ''')

4) 将您的静态文件存储在应用程序中名为 static 的文件夹中。例如: my_app/static/my_app/myimage.jpg.

这是我的目录结构:

(django186p34)~/django_projects$ tree mysite2

mysite2
├── db.sqlite3
├── manage.py
└── mysite2
    ├── __init__.py

    ├── settings.py
    ├── static           #<****HERE*****
    │   └── mysite2
    │       └── Aerial03.jpg
    ├── urls.py
    ├── views.py
    └── wsgi.py

4 directories, 13 files

但是启动服务器后:

(django186p34)~/django_projects/mysite2$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
November 26, 2015 - 02:44:57
Django version 1.8.6, using settings 'mysite2.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

然后在我的浏览器中导航到:

http://localhost:8000/

我看到文字:

Hello

但是找不到图片:

[错误] 加载资源失败:服务器响应状态 404 http://localhost:8000/static/mysite2/Aerial03.jpg

我在 html 中尝试了很多 url 的组合,但没有任何效果。

这里是settings.py的全部内容(我没有做任何改动):

"""
Django settings for mysite2 project.

Generated by 'django-admin startproject' using Django 1.8.6.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

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/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pmaup3%)m09cs2goldduw2iogso%(#8cz0s-zmr%*e'

# 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',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite2.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 = 'mysite2.wsgi.application'


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

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


# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/

STATIC_URL = '/static/'

这个固定的东西:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mysite2',  #<*****HERE*****
)

并且如果您组织事物以便在项目中包含应用程序,例如:

(django186p34)~/django_projects$ tree mysite3
mysite3
├── db.sqlite3
├── manage.py
├── myapp
│   ├── __init__.py

│   ├── admin.py
│   ├── migrations
│   │   

│   │    
│   ├── models.py
│   ├── static
│   │   └── myapp
│   │       └── Aerial03.jpg
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── mysite3
    ├── __init__.py

    ├── settings.py
    ├── urls.py
    └── wsgi.py

8 directories, 24 files

然后在 settings.py 中将您的应用程序名称添加到 INSTALLED_APPS:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  #<*****HERE*****
)

默认 settings.py 中的其他所有内容保持不变。但是,url 不同:

mysite3/mysite3/urls.py:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),

    url(r'^myapp/', include('myapp.urls')),
]

mysite3/myapp/urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

在您的浏览器中,url 变为:

http://localhost:8000/myapp/

myapp/views.py:

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse


def index(request):
    return HttpResponse('''

        <h2>Hello</h2>
        <img src="/static/myapp/Aerial03.jpg">


    ''')