首页 > 技术文章 > django 静态文件&&模版的处理的一些实践

rongfengliang 2021-01-02 15:13 原文

静态文件与模版在django 中的处理既有相似的地方又有不同的地方
模版是代码关联的,静态文件一般是css,js ,图片等,一般静态资源是需要进行比较好的处理的(量大,而且需要优化处理)

静态资源的处理

  • 配置
    参考,注意app 以及project的会有覆盖的效果,这个与template是一样的
 
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
  • 优化处理
    推荐配置STATIC_ROOT,这样在实际生成部署的使用,使用静态资源模式拆分(nginx,apache.cdn....)
    命令
 
python manage.py collectstatic

好处是可以静态资源的聚合,方便镜像资源的独立服务提供,但是可能会有冲突的问题(所以比较好的静态资源前缀命名就很重要的)

  • 代码使用
    推荐使用static 模版tag,可以减少路径配置死
 
{% load static %}
<html>
<head >
    <link rel="stylesheet" type="text/css" href="{% static 'userlogin/app.css' %}">
</head>
  <div>
      this is userlogin demo app
  </div>
</html>

模版的处理

模版与静态资源类似,但是是代码关联的,同时也会有覆盖的问题,一般推荐的写法如下

  • 参考配置
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',
            ],
        },
    },
]

处理是方便app 的可复用(打包为pip 包,同时我们也可以基于项目级别的templates 进行覆盖)

参考资料

https://www.digitalocean.com/community/tutorials/working-with-django-templates-static-files
https://docs.djangoproject.com/en/3.1/topics/templates/
https://docs.djangoproject.com/en/3.1/howto/overriding-templates/
https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/#django-admin-collectstatic
https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATIC_ROOT
https://docs.djangoproject.com/en/3.1/howto/static-files/

推荐阅读