CentOS 6.8 部署django项目二

CentOS 6.8 部署django项目一

1、项目部署后发现部分页面的样式丢失,是因为在nginx中配置的static路径中未包含。

解决:在settinfs.py中添加:

STATIC_ROOT = os.path.join(BASE_DIR, "static_all")

 然后执行:

python3 ./manage.py collectstatic

 项目下自动生成static_all文件夹,里面包含所有的静态文件,然后修改nginx的配置文件,指向该文件路径。

2、自定义模板参数

如果希望向页面传递参数,类似于{{MEDIA_URL}}这种,我们可以模仿django添加自己的处理方法:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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',
                # 'django.template.context_processors.media',  # 配置html页面获取MEDIA_URL路径
                'configs.sysconf.media'
            ],
        },
    },
]

 注释掉django的django.template.context_processors.media,添加自己的configs.sysconf.media,内容是:

from configs.models import ServerConfig


def media(request):
    """
    Adds media-related context variables to the context.
    """
    try:
        serverConfig = ServerConfig.objects.all()[0]
        image_server = serverConfig.img_server_ip + ':' + serverConfig.img_server_port.__str__()
    except Exception:
        image_server = '127.0.0.1'

    return {'MEDIA_URL': 'http://' + image_server + '/images/',
            'VOD_URL': image_server + '/vods/',
            'ANNEX_URL': image_server + '/annexs/',
            }

 这样就可以在页面配置模板参数。

原文地址:https://www.cnblogs.com/lanqie/p/7802432.html