Django部署到服务器后无法获取到静态元素 The requested resource was not found on this server

问题描述

Django项目部署到服务器后无法获取到静态元素 The requested resource was not found on this server。如图:

原因分析

  • 当 DEBUG = False 时,Django 不会自动提供静态文件服务
  • urls.py 中,静态文件的路由是通过 static() 函数添加的,但这个函数只在 DEBUG = True 时才会生效
  • 静态文件存储在 media/files 目录下,通过 /media/ URL 访问

解决方案

  1. 修改环境配置backend/conf/env.py 中添加:

    python 复制代码
    DEBUG = False
    SERVE_STATIC_FILES = True  # 新增配置项
  2. URL配置已自动处理

    项目已配置了媒体文件路由,确保在生产环境中也能访问:

    python 复制代码
    path("media/<path:file_path>", server_file, name="media_file"),
  3. 改进的server_file视图

    backend/dvadmin/system/views/server_file.py 优化,包含:

    • 路径安全检查
    • MIME类型支持
    • 错误处理
    • 多种文件格式支持
python 复制代码
   def server_file(request, file_path):
    """
    处理媒体文件访问的视图
    用于在生产环境中提供静态文件服务
    
    Args:
        request: HTTP请求对象
        file_path: 文件路径(从URL中获取)
    """
    # 清理文件路径
    file_path = file_path.lstrip('/')
    
    # 构建完整的文件路径
    full_path = os.path.join(settings.MEDIA_ROOT, file_path)
    
    # 安全检查:确保文件路径在MEDIA_ROOT目录内
    if not os.path.abspath(full_path).startswith(os.path.abspath(settings.MEDIA_ROOT)):
        raise Http404("文件路径无效")
    
    # 检查文件是否存在
    if not os.path.exists(full_path) or not os.path.isfile(full_path):
        raise Http404("文件不存在")
    
    # 获取文件扩展名
    file_ext = os.path.splitext(full_path)[1].lower()
    
    # 设置MIME类型
    mime_types = {
        '.pdf': 'application/pdf',
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.bmp': 'image/bmp',
        '.svg': 'image/svg+xml',
        '.txt': 'text/plain',
        '.doc': 'application/msword',
        '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        '.xls': 'application/vnd.ms-excel',
        '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        '.zip': 'application/zip',
        '.rar': 'application/x-rar-compressed',
        '.7z': 'application/x-7z-compressed',
        '.mp4': 'video/mp4',
        '.avi': 'video/x-msvideo',
        '.mp3': 'audio/mpeg',
        '.wav': 'audio/wav',
    }
    
    content_type = mime_types.get(file_ext, 'application/octet-stream')
    
    try:
        # 返回文件响应
        response = FileResponse(open(full_path, 'rb'), content_type=content_type)
        
        # 设置文件名(用于下载)
        filename = os.path.basename(full_path)
        response['Content-Disposition'] = f'inline; filename="{filename}"'
        
        return response
    except Exception as e:
        raise Http404(f"文件访问失败: {str(e)}")
相关推荐
qq_22589174669 小时前
基于Python的城市内涝积涝监测数据可视化分析系统
后端·python·信息可视化·数据分析·django
米码收割机10 小时前
【Python】Python Django+Vue3校园自习室预约管理系统(源码+文档+PPT)【独一无二】
开发语言·python·django
米码收割机12 小时前
【移动】线上购物移动端网站(源码+文档)【独一无二】
java·开发语言·前端·python·django
weixin_BYSJ19871 天前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php
智购科技自动售货机工厂1 天前
即时零售的风吹到自动售货机行业,会带来什么变化?~YH
大数据·人工智能·django·fastapi·零售·tornado
想你依然心痛1 天前
预测未来用电趋势,机器学习算法在能耗管理中的落地
随机森林·django·数据清洗·特征工程·电力负荷预测·时序数据·能耗管理
倒流时光三十年2 天前
第一阶段 02 · Mapping 与数据类型(text vs keyword 是重点)
后端·python·django
weixin_BYSJ19873 天前
springboot3家政平台小程序--附源码00904
java·javascript·spring boot·python·django·flask·php
米码收割机4 天前
【Python】Django 电子设备商城系统(源码+说明文档)[独一无二]
开发语言·python·django
dNGUZ7UGj5 天前
10分钟完成第一个Python小游戏
python·django