码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-01-10 18:45:00      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:file   ima   files   bug   deploy   python   htm   import   静态资源   

目录结构:

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

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

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

标签:file   ima   files   bug   deploy   python   htm   import   静态资源   

原文地址:https://www.cnblogs.com/df888/p/12177468.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!