django 应用程序静态文件在生产中不起作用

django application static files not working in production

即使对于管理页面,静态文件在生产环境中也不起作用。

我没有添加任何静态文件。

我的管理页面样式有问题。

我已经按照以下教程创建了 django 应用程序。

https://tutorial.djangogirls.org/en/

下面是我的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__)))


# 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 = '##############################'

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

ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog', ]

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 = 'new_p.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 = 'new_p.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/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')

我已经 运行 生产中的 collectstatic。

(master)$ python3 manage.py collectstatic

You have requested to collect static files at the destination location as specified in your settings:

    /home/ag/ag.pythonanywhere.com/new_p/static

This will overwrite existing files! Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

0 static files copied to '/home/agusm/agusm.pythonanywhere.com/new_p/static', 119 unmodified.

将静态文件投入生产的基本轮廓很简单运行 collectstatic 命令

您需要配置您的网络服务器以提供 STATIC_ROOT 中的文件 URL STATIC_URL

参考这个link

Here is what you need

当 collectstatic 为 运行 时,默认 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.FileSystemFinder 将从您在 STATICFILES_DIRS.

中的任何路径收集静态文件

另一个默认 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.AppDirectoriesFinder 将在您 INSTALLED_APPS 中的任何应用程序的 /static/ 文件夹中查找。

找到的所有静态文件都将放在指定的 STATIC_ROOT 目录中。

$ python manage.py collectstatic

这会将静态文件夹中的所有文件复制到 STATIC_ROOT 目录中。

您也可以使用

python manage.py findstatic

查看 collectstatic 将查找哪些目录。

如果你使用 nginx,你需要在你的配置中加入这个

server{
...
    location /static/ {
        alias /path/to/static/;
        ...
    }
...
}

像这样的 apache

<VirtualHost *:80>
...
Alias /static "/path/to/static/"  
<Directory "/path/to/static">  
    Order allow,deny
    Allow from all 
</Directory>
</VirtualHost>

我认为你的设置和方式 运行 collectstatic 很好。

如果您在 pythonanywhere 上托管,我假设您是基于 ALLOWED_HOSTS,您需要遵循 this guide:

Set up a static files mapping

Finally, set up a static files mapping to get our web servers to serve out your static files for you.

Go to the Web tab on the PythonAnywhere dashboard Go to the Static Files section Enter the same URL as STATIC_URL in the url section (typically, /static/) Enter the path from STATIC_ROOT into the path section (the full path, including /home/username/etc)

Then hit Reload and test your static file mapping by going to retrieve a known static file.

Eg, if you have a file at /home/myusername/myproject/static/css/base.css, go visit http://www.your-domain.com/static/css/base.css

这基本上就是您通过设置网络服务器(nginx/apache 与 中一样)手动执行的操作,但我假设它正在执行通过 pythonanywhere 的网络界面设置目录别名的相同过程相反。

将这些文本粘贴到 settings.py 文件中

STATIC_URL = '/static/'
STATICFILES_DIRS=[os.path.join(BASE_DIR,"static"), "templates"]

MEDIA_URL="static/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media/")

然后将 {% load static %} 粘贴到要使用静态文件或媒体的 html 文件中

然后对图像使用 <img src="{% static 'media/images/mandeep.jpeg' %}" alt="My image">

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

有任何问题欢迎提问