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)}")
相关推荐
Muyuan199811 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
程序媛徐师姐16 小时前
Python基于Django的小区果蔬预定系统【附源码、文档说明】
python·django·小区果蔬预定系统·果蔬预定·python小区果蔬预定系统·小区果蔬预定·python果蔬预定系统
码界筑梦坊2 天前
111-基于Python的中国旅游用户数据可视化分析系统
python·信息可视化·django·毕业设计·旅游
YJlio2 天前
10.2.8 以其他账户运行服务(Running services in alternate accounts):为什么“把服务切到某个用户账号下运行”,本质上是在改变服务的整个安全上下文?
python·安全·ios·机器人·django·iphone·7-zip
小熊Coding2 天前
懂车帝汽车销售数据可视化分析系统
python·信息可视化·django·汽车·数据可视化分析·懂车帝·汽车销售数据分析
ma_de_hao_mei_le2 天前
ntquerysystemiunfomation 数据传递
django
Muyuan19983 天前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi
Muyuan19983 天前
25.Paper RAG Agent 优化记录:上传反馈、计算器安全与 Chunk 参数调整
python·安全·django·sqlite·fastapi
Muyuan19983 天前
26.Paper RAG Agent 展示面收口:截图与项目表达更新记录
人工智能·python·django·fastapi
毕胜客源码4 天前
卷积神经网络的手势识别系统(有技术文档)深度学习 图像识别 卷积神经网络 Django python 人工智能
人工智能·python·深度学习·cnn·django