You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板继承后子模板静态轮播图404加载失败问题排查

问题根源

你在base.html里写的轮播图路径是不带绝对路径的相对路径,触发了浏览器的相对路径拼接规则:

  • 访问首页/时,相对路径static/img/xxx.jpg会被浏览器解析为根路径下的/static/img/xxx.jpg,刚好匹配Django的静态资源路由,所以正常加载
  • 访问搜索页/search/时,相对路径会自动拼到当前URL的同级层级下,变成/search/static/img/xxx.jpg,Django没有配置这个路由,所以返回404
    日志里的404报错路径完全对应这个问题,和你设置的APP_DIRS = False、旧的Search应用残留没有关系。
    另外base.html里导航栏的跳转链接href="wind_index.html"也是同样的相对路径问题,只是你还没点击触发报错而已。
具体修复步骤
    1. 替换base.html里所有静态资源的引用,全部改用Django的{% static %}模板标签解析绝对路径,禁止直接写裸的相对路径
      原来的错误写法:
    <img src="static/img/rsz_kitesurfing1920x9083.jpg" class="d-block w-100" class="img-fluid" alt="kite1">
    <img src="static/img/kite3.jpg" class="d-block w-100" class="img-fluid" alt="kite2">
    <img src="static/img/kitesurfing1920x908(1).jpg" class="d-block w-100" class="img-fluid" alt="kite3">
    
    改成正确写法(base.html已经加载了{% load static %},直接用就行):
    <img src="{% static 'img/rsz_kitesurfing1920x9083.jpg' %}" class="d-block w-100 img-fluid" alt="kite1">
    <img src="{% static 'img/kite3.jpg' %}" class="d-block w-100 img-fluid" alt="kite2">
    <img src="{% static 'img/kitesurfing1920x908(1).jpg' %}" class="d-block w-100 img-fluid" alt="kite3">
    
    注:这里要确保你的图片文件实际存放在API/static/img/目录下,才能被{% static 'img/xxx.jpg' %}正确解析
    1. 修正base.html里的页面跳转链接,不要直接写模板文件名,要指向Django配置的路由
      原来的错误写法:
    <a class="navbar-brand" href="wind_index.html">Wind Portal</a>
    <a class="nav-link" href="wind_index.html">Home <span class="sr-only">(current)</span></a>
    <a class="nav-link" href="#">Wind search</a>
    
    改成正确写法(如果你的路由配了名称,用{% url '路由名' %}反向解析最稳妥,临时可以直接写路由路径):
    <a class="navbar-brand" href="/">Wind Portal</a>
    <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
    <a class="nav-link" href="/search/">Wind search</a>
    
    1. 修正settings.py里的STATICFILES_DIRS配置,避免相对路径导致的静态资源找不到问题
      原来的配置用了相对路径,容易受项目启动目录影响,改成绝对路径拼接:
    # 原配置:
    # STATICFILES_DIRS = (
    #     'WindPortal/API/static',
    #     'static/img',
    # )
    # 改成:
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'API', 'static'),
        # 如果你的图片不是放在API/static/img下,而是放在项目根目录的static/img下,才加下面这行,否则删掉
        os.path.join(BASE_DIR, 'static', 'img'),
    ]
    
补充说明

你设置的APP_DIRS = False完全没问题,这个配置只是控制Django是否自动从每个应用的templates目录查找模板,你现在所有模板都放在API/templates下,并且已经在TEMPLATES的DIRS里配置了这个路径,所以这个设置不会影响模板加载,也和当前的静态资源404问题无关。

内容的提问来源于stack exchange,提问作者marv8569

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 07:24:04