简体   繁体   English

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

[英]django application static files not working in production

static files are not working in production even for the admin page.即使对于管理页面,静态文件也无法在生产中工作。

I have not added any static files.我没有添加任何静态文件。

I am having issues with my admin page style.我的管理页面样式有问题。

I have followed the below tutorial to create the django application.我按照以下教程创建了 django 应用程序。

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

below is my settings.py下面是我的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')

I have already run collectstatic in production.我已经在生产中运行了 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.

I think your settings and the way you run collectstatic is fine.我认为您的设置和运行collectstatic方式很好。

If you are hosting on pythonanywhere , which I assume you are based on your ALLOWED_HOSTS , you need to follow this guide :如果你在pythonanywhere上托管,我假设你是基于你的ALLOWED_HOSTS ,你需要遵循这个指南

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.最后,设置一个静态文件映射,让我们的 Web 服务器为您提供静态文件。

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)转至 PythonAnywhere 仪表板上的 Web 选项卡 转至静态文件部分 在 url 部分中输入与 STATIC_URL 相同的 URL(通常为 /static/) 将 STATIC_ROOT 的路径输入到路径部分(完整路径,包括 /home/用户名/等)

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例如,如果您在 /home/myusername/myproject/static/css/base.css 有一个文件,请访问http://www.your-domain.com/static/css/base.css

This is basically what you would do manually by setting up your webserver (nginx/apache as in pfitzer's answer ), but I assume it's doing the same process of setting a directory alias via pythonanywhere's web interface instead.这基本上是您通过设置网络服务器(如pfitzer's answer 中的nginx/apache )手动执行的操作,但我认为它正在执行相同的过程,即通过 pythonanywhere 的网络界面设置目录别名。

If you use nginx you need this in your config如果你使用 nginx 你需要在你的配置中

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

For apache like this对于这样的 apache

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

The basic outline of putting static files into production is simple run the collectstatic command将静态文件投入生产的基本轮廓很简单,运行collectstatic命令

you need to configure your web server to serve the files in STATIC_ROOT under the URL STATIC_URL您需要配置您的 Web 服务器以在 URL STATIC_URL下提供STATIC_ROOT 中的文件

refer this link参考这个链接

Here is what you need 这是你需要的

When collectstatic is run, the default STATICFILES_FINDERS value django.contrib.staticfiles.finders.FileSystemFinder will collect your static files from any paths that you have in STATICFILES_DIRS.当 collectstatic 运行时,默认的 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.FileSystemFinder 将从您在 STATICFILES_DIRS 中拥有的任何路径收集您的静态文件。

The other default STATICFILES_FINDERS value django.contrib.staticfiles.finders.AppDirectoriesFinder will look in the /static/ folder of any apps in your INSTALLED_APPS.另一个默认的 STATICFILES_FINDERS 值 django.contrib.staticfiles.finders.AppDirectoriesFinder 将查看 INSTALLED_APPS 中任何应用程序的 /static/ 文件夹。

All of the static files that are found will be placed in the specified STATIC_ROOT directory.找到的所有静态文件都将放置在指定的 STATIC_ROOT 目录中。

$ python manage.py collectstatic

This will copy all files from your static folders into the STATIC_ROOT directory.这会将静态文件夹中的所有文件复制到 STATIC_ROOT 目录中。

You can also use你也可以使用

python manage.py findstatic

to see which directories collectstatic will look in.查看 collectstatic 将查找哪些目录。

paste these text in the settings.py file将这些文本粘贴到 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/")

then paste {% load static %} in the html file where you want to use the static files or media然后将{% load static %}粘贴到要使用静态文件或媒体的 html 文件中

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

and for css link use <link rel="stylesheet" href="{% static '/css/style.css' %}">对于 css 链接使用<link rel="stylesheet" href="{% static '/css/style.css' %}">

feel free to ask any question随时提出任何问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM