django2.2 DEBUG=True/False时如何设置静态文件(image js css等)

目录结构:

project
----templates
----app
----manage.py

添加静态资源,目录结构更新为:

project
----templates
----app
----static  # 静态资源
--------img
--------js
--------css
----manage.py

以img举例,引用资源的代码为:

{% load static %}
<img src='{% static "img/favicon.png" %}'/>

DEBUG = True

django会自动调用django.views.static.serve()来自动找。

settings.py中指定STATICFILES_DIRS即可:

# settings.py
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app/static/')
]

DEBUG = False

django不会自动找了,需要手动添加。

  1. settings.py中指定STATIC_ROOT

    # settings.py
    STATIC_URL = '/static/'
    
    STATIC_ROOT = 'static'  # project根目录下
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'app/static/')
    ]
  2. urls.py中手动调django.views.static.serve()

    from django.views.static import serve
    urlpatterns = [
        url(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT})
    ]
  3. 此时访问还是会发现404,因为STATIC_ROOT是在deploy时,统一存放静态资源的目录,此时这个目录根本就没有文件,需要手动执行collectstatic来拷贝文件。

    python manage.py collectstatic

    遇到重复文件,会有错误提示:

    This will overwrite existing files!
    Are you sure you want to do this?
    
    Type 'yes' to continue, or 'no' to cancel:

以上就总结了DEBUG=True/False时设置静态文件的方法。

觉得有用的同学可以顺手关注下或点个赞哦!

参考文档:

django.contrib.staticfiles.views.serve: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#django.contrib.staticfiles.views.serve

Managing static files: https://docs.djangoproject.com/en/dev/howto/static-files/

Deploying static files: https://docs.djangoproject.com/en/dev/howto/static-files/deployment/

collectstatic: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#django-admin-collectstatic

版权申明:本文为博主原创文章,转载请保留原文链接及作者。

相关推荐