Django应用程序静态文件在生产环境中无法使用。

6

生产环境中静态文件即使对于管理员页面也无法工作。

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

我的管理员页面样式出现问题。

我按照下面的教程创建了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吗?你使用什么Web服务器来托管Django项目? - ritlew
是的,我已经运行了collectstatic。 - Okay
2
你是否配置了Web服务器,将/static指向collectstatic放置文件的文件夹? - ritlew
1
Django本身不提供文件服务,而是将这项工作留给您选择的Web服务器来完成。 - rahul.m
@c.grey添加了settings.py,抱歉耽搁了。 - Okay
显示剩余3条评论
6个回答

5

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

如果您正在使用pythonanywhere进行主机托管,我假设您是这样做的,那么您需要按照此指南操作:

设置静态文件映射

最后,设置一个静态文件映射以便让我们的Web服务器为您提供静态文件。

进入PythonAnywhere控制面板上的Web选项卡 进入静态文件部分 在url栏中输入STATIC_URL相同的URL(通常是/static/) 在路径部分中输入STATIC_ROOT中的路径(包括/home/username/etc在内的完整路径)

然后点击“重新加载”并通过检索已知的静态文件来测试您的静态文件映射。

例如,如果您有一个文件位于/home/myusername/myproject/static/css/base.css,则请访问http://www.your-domain.com/static/css/base.css

基本上,这就是您手动设置Web服务器(如pfitzer的回答中所述的nginx/apache)所做的操作,但我假设它是通过pythonanywhere的Web界面设置目录别名来完成相同的过程。


我没有任何静态文件。 - Okay
是的,我明白。那些是静态文件,collectstatic 从 Django 中收集它们并将它们放在一个目录中,以便 Django 可以提供服务。我不明白你还在问什么,你试过上面的方法了吗? - Geekfish
你是否尝试按照上述描述设置PythonAnywhere设置? - Geekfish
你的问题具体表现是什么?如果你在浏览器中打开网络选项卡,是否会出现CSS/JS文件的404错误?请求路径是否符合你的期望? 此外,如果你检查访问日志(在服务器上),是否能看到这些请求和404错误?也许那里有一些有用的信息。 - Geekfish
1
你设置了哪些PythonAnywhere静态映射?在设置完这些静态映射后,你是否重新加载了Web应用程序? - conrad
显示剩余2条评论

3
如果你使用nginx,你需要在配置文件中加入以下内容:
```最初的回答```
server{
...
    location /static/ {
        alias /path/to/static/;
        ...
    }
...
}

For apache like this

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

“autoindex on” 不是必需的,实际上可能不需要。我建议将其删除。 - Geekfish

1
主要问题在于您创建的项目的urls.py文件中,我也找到了解决方案: 如果DEBUG = False,那么Django的默认设置不包括静态和媒体路径。 urls.py:
urlpatterns = [
    path('', include('<app_name>.urls')),   
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
 urlpatterns += path('admin/', admin.site.urls)

settings.py:

STATIC_URL = 'Assets/'
STATIC_ROOT = BASE_DIR / 'staticfiles_build' / 'Assets'
STATICFILES_DIRS = [
    BASE_DIR / "Assets",
]

Assets是存放静态文件的文件夹名称,你的情况下可能是static。


0
将静态文件上线的基本步骤很简单,只需要运行collectstatic命令即可。
您需要配置您的Web服务器以在URLSTATIC_URL下提供STATIC_ROOT中的文件。
请参考此链接link

-1

这里是你需要的

当运行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 将搜索哪些目录。


-2

将这些文本粘贴到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/")

然后在您想要使用静态文件或媒体的HTML文件中粘贴{% load static %}

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

对于CSS链接,请使用<link rel="stylesheet" href="{% static '/css/style.css' %}">

如有任何问题,请随时提问


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接