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

时间:2015-11-26 02:58:17

标签: static-files django-1.8

我试图按照名为Managing static files的Django文档中的部分进行操作。我有兴趣找到:

  1. 我做错了什么。
  2. 或者,Django文档出了什么问题。
  3. 1) 确保您的INSTALLED_APPS中包含django.contrib.staticfiles。

    在默认的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) 在您的模板中,对网址进行硬编码,如 /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中尝试了很多网址组合,但没有任何效果。

    以下是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/'
    

1 个答案:

答案 0 :(得分:0)

这个固定的东西:

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中的其他所有内容都保持不变。但是,网址不同:

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

在您的浏览器中,网址变为:

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">


    ''')