django static如何正常工作

时间:2016-07-31 14:27:26

标签: python django static

我一直使用PHP,最后决定离开那个洞穴并探索其他脚本语言,如django。

我仍然围绕着django的项目结构,并且似乎无法弄清楚如何包含css,js和其他所谓的静态文件。

我已经阅读了django wiki,我知道我应该使用静态来引用这些文件。但为了做到这一点,我需要在settings.py中定义我的静态目录。

我注意到当我调用static {% 'filename.extension' %}时,它会将文件附加到settings.py中定义的静态目录。但是,如果我理解这一点就行了。问题是我有一些html代码试图从localhost:8000/static/directory/filename.extension获取文件但是由于python处理url的方式不同,html代码不会从这样的url获取任何文件因此我的css不会被加载

我的settings.py

我的文件结构:

PassWard >
    PassWard >
        __pycache__ >
        wardvault >
            __pucache__ >
                ... (pycache stuff) ...
            templates >
                imports.html
                menu.html
                wardvault >
                    base.html
                    passwords.html
            migrations >
                ... (migration stuff) ...
            __init__.py
            admin.py
            admin.pyc
            apps.py
            models.py
            models.pyc
            tests.py
            views.py
            views.pyc
        __init__.py

    static >
        font_awesome >
            ... (lots of font related files) ...
        js >
            jquery.min.js
        imports.html
        menu.css
        menu.html
        menu.js
        reset.css
    db.splite3
    manage.py

我的settings.py看起来像是:

"""
Django settings for PassWard project.

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

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

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

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't+*07vdh&h^c*2ito-9_ywo^mcxps1o$e@^gb$%6vy7m5vr_^3'

# 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',
    'PassWard.wardvault',
]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    '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',
]

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


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

STATIC_URL = '/static/'

我正在尝试将静态文件加载到passwords.html内的wardvault

我试图访问静态文件的html snippit如下所示:

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

{% static '/static/menu.css' %}的结果/static/menu.css只是static

我的问题是,当我使用settings.py时,它只是将STATIC_URL中定义的内容附加到参数中吗?如果是这样,当/static/设置为registry.addMapping("/**").allowedOrigins("http://localhost:8090") .allowedMethods("PUT", "DELETE", "GET", "POST"); 时,第一个斜杠是指从项目根目录还是系统根目录开始?我也正确使用它?或者有什么我想念的东西?

随意指出项目结构的不良做法。我仍然试图绕过一切。

1 个答案:

答案 0 :(得分:1)

在模板中使用static标记时:

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

只需将{% static部分替换为STATIC_URL值即可进行扩展。所以标签变成:

<link rel="stylesheet" type="text/css" href="/static/static/menu.css" />

你知道,现在有2 /static/。鉴于它以斜杠开头,它将在应用程序的根目录中查找。现在,根据您的目录结构,您的代码应该只是:{% static 'menu.css' %}

现在来讨论如何提供文件?有两个选项:

  1. 当您运行开发服务器时,您可以让django的静态应用程序为该文件提供服务。 Django - serving static files during development

  2. 在生产服务器中,您可以让nginx或apache提供静态文件。查看Django staticfiles "deployment" section

  3. 与静态应用相关的其他重要设置是STATIC_ROOT。它是用于存储所有静态资产的路径。这就是python manage.py collectstatic命令将收集静态文件的位置。因此,理想情况下,nginx或apache中的STATIC_URL位置应该别名到该目录。