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'

相关推荐
数字化转型分享点滴22 分钟前
## 工厂数字化管理系统的价值体现:构建制造全流程数据闭环
python
朦胧之33 分钟前
PostgreSQL 数据库笔记
人工智能·后端
2301_800074211 小时前
map,list简单方法
windows·python·list
DeepVisionary2 小时前
30B 参数打平 1 万亿参数:Meta 开源 Muse Glimmer,跑分 35 对 36
python·自动化
吴声子夜歌2 小时前
Guava——基本工具(二)
windows·python·guava
IT_陈寒3 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
LucianaiB3 小时前
用 WorkBuddy 研究腾讯、阿里和 DeepSeek,我没敢直接说「AI 很赚钱」
后端
用户8356290780513 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
分支预测失败4 小时前
RISC-V 上下文切换实战:从 Trap 入口到 Linux 进程调度
后端·嵌入式
猎嘤一号4 小时前
【2026 最新】Windows 11 右键菜单还原为 Windows 10 经典样式:一条命令、原理、回退与新版说明
windows·python