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

相关推荐
invicinble3 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
小码哥_常3 小时前
MyBatis-Plus:让数据库操作飞起来的神器
后端
2301_811274313 小时前
基于SpringBoot的智能家居管理系统
spring boot·后端·智能家居
AI人工智能+电脑小能手3 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
舒一笑4 小时前
我把设备指纹生成逻辑拆开了:它到底凭什么区分不同设备?
后端·程序员·掘金技术征文
m0_674294644 小时前
如何编写SQL存储过程性能对比_记录执行时间评估优化效果
jvm·数据库·python
运气好好的4 小时前
怎样开启phpMyAdmin的操作审计日志_记录每条执行的SQL
jvm·数据库·python
Nicander4 小时前
多数据源下@transcation事务踩坑
java·后端
郑州光合科技余经理4 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
2401_871492855 小时前
Layui如何修改Layui默认的UI主题颜色(换肤功能实现)
jvm·数据库·python