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

相关推荐
西红市杰出青年4 分钟前
asyncio.gather 内部原理与运行机制(详解)
网络·python·异步
70asunflower6 分钟前
torch.manual_seed()介绍
人工智能·pytorch·python
西红市杰出青年14 分钟前
Playwright 的 BrowserContext 与 Page:原理与实践指南
python
源代码•宸17 分钟前
Leetcode—3. 无重复字符的最长子串【中等】
经验分享·后端·算法·leetcode·面试·golang·string
Tianwen_Burning18 分钟前
pycharm下配置halcon
python
汉堡go20 分钟前
python_chapter6
前端·数据库·python
摘星编程27 分钟前
React Native鸿蒙:Geolocation持续定位更新
python
小二·44 分钟前
Python Web 开发进阶实战:数字孪生平台 —— 在 Flask + Vue 中构建实时物理世界镜像
前端·vue.js·python
0和1的舞者1 小时前
基于Spring的论坛系统-前置知识
java·后端·spring·系统·开发·知识
2501_942158431 小时前
服务设计从成本到利润引擎的重构
大数据·python·重构