django windows 静态文件 404

settings.py 静态文件相关配置如下

python 复制代码
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

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

问题描述

python 复制代码
[13/Jul/2023 16:15:44] "GET /static/image/cat.jpg HTTP/1.1" 404 1798 

解决方法

对于windows增加配置STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )

配置完后setting.py相应部分具体如下:

python 复制代码
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )  # Used for windows static files.
STATIC_DIRS = (os.path.join(BASE_DIR, 'static'),)

扩充:

STATIC_URL = '/static/' 该/static/为浏览器地址栏里http://127.0.0.1:8000/static/image/cat.jpg的static

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

STATIC_DIRS = (os.path.join(BASE_DIR, 'static'),)

里的static为项目文件目录里的static,具体如下:

PS E:\code\xxx\xxx\portrait\static\image> ls

目录: E:\code\xxx\xxx\portrait\static\image

Mode LastWriteTime Length Name


-a---- 2023/7/13 15:55 95727 cat.jpg

PS E:\code\xxx\xxx\portrait\static\image>

所以对于模板里的img标签url,<img src="http://127.0.0.1:8000/static/image/cat.jpg" width="200px" height="200px">

前半部分为settings.py里STATIC_URL确定,后半部分为settings.py里STATICFILES_DIRS和STATIC_DIRS来关联本地路径。

另外如果不能访问静态文件出现5xx时记得检查本地地址在settings.py的ALLOWED_HOSTS里。

ALLOWED_HOSTS = '123.123.123.123', '127.0.0.1'

相关推荐
犀利豆5 小时前
Claude code tools 研究系列(二)EnterPlanMode
人工智能·后端
alphaTao5 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
用户69371750013845 小时前
AI时代,程序员该往哪走?
前端·后端
Kevin Wang7275 小时前
Nvidia-AGX-spark部署手册——课堂质量诊断(jetpack:r36)
python·docker·容器
Revolution615 小时前
第一次运行 Node.js:终端里的 JavaScript 怎样执行
后端·面试·node.js
Python私教6 小时前
Django 6.1 RC1 实测:FETCH_PEERS 两条 SQL 解决 N+1,select_related 还需要吗?
后端·python·django
大侠在此在在此6 小时前
教你用最简单的数学自底向上地高效学习SQL注入
后端
玉鸯6 小时前
Agent 的任务编排:从 System Prompt 到 Hierarchical Multi-Agent
python·llm·agent
Python私教6 小时前
Django 6.0 自带 Tasks 到底能不能替代 Celery?跑完 3 组后台任务后我有答案了
后端·python·django
我的xiaodoujiao7 小时前
快速学习Python基础知识详细图文教程14--模块
开发语言·python·学习·测试工具