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']

相关推荐
不要em0啦10 分钟前
从0开始学python:判断与循环语句
开发语言·python
OC溥哥99911 分钟前
2D我的世界创造模式网页版正式出炉——《我们的2D创造世界:无限创意,多人同乐》欢迎来到ourcraft.xin网站上玩
后端·python·阿里云·flask·html·游戏程序
SCBAiotAigc38 分钟前
langchain1.2学习笔记(一):安装langchain
人工智能·python·langchain
亓才孓1 小时前
java中的Math.Radom拓展
开发语言·python·算法
laocooon5238578861 小时前
Rust 编程语言教学目录
开发语言·后端·rust
小希smallxi1 小时前
Rust语言入门
开发语言·后端·rust
默 语1 小时前
Spring Boot 3.x升级踩坑记:到底值不值得升级?
hive·spring boot·后端
Java编程爱好者1 小时前
JDK 21 中的虚拟线程:革新 Java 多线程
后端
悟能不能悟1 小时前
springboot controller返回的是HttpServletResponse成功返回excel文件流,失败就返回失败参数
spring boot·后端·excel
神奇小汤圆1 小时前
面试官:如何在 Kafka 中实现延迟消息?
后端