返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
0_Django基础知识

Static File Handling in Django Applications

In daily development, we always turn on Django's Debug mode for easier debugging. In this mode, Django's built-in web server serves static files, but some configuration is needed to access them correctly. Configure settings # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ ST

曦远 (DealiAxy)约 6 分钟
目录4 个章节

In daily development, we always turn on Django's Debug mode for easier debugging. In this mode, Django's built-in web server serves static files, but some configuration is needed to access them correctly.

Configure settings

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

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

STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
MEDIA_URL = '/media/'

Configure routing

from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static

urlpatterns = [
    ...
]

# 调试模式下的静态文件服务
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This way you can access static files normally in Debug mode. However, after we deploy the application to production, Debug mode must not be enabled for security reasons. At that point you need to use a server such as nginx or Apache to serve static files.

Before that, you also need to run

python manage.py collectstatic

to collect static files from the various packages into the STATIC_ROOT we defined earlier, and then hand this path over to nginx~

nginx configuration

# Django media
location /media/  {
    alias /path/to/django/static/media/;  # your Django project's media files - amend as required
}

location /static/ {
    alias /path/to/django/static_collected/; # your Django project's static files - amend as required
}

Also disable Django's Debug mode, so that all static files will be served by nginx~

Welcome to discuss

I've compiled a series of technical articles and materials. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, and so on in the backend of the WeChat official account 「程序设计实验室」 to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Static File Handling in Django Applications

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…