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)}")
相关推荐
Q_Q51100828513 小时前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
Q_Q51100828518 小时前
python+uniapp基于微信小程序的学院设备报修系统
spring boot·python·微信小程序·django·flask·uni-app
liweiweili12620 小时前
Django中处理多数据库场景
数据库·python·django
workflower1 天前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
局外人LZ2 天前
django rest framework:从零开始搭建RESTful API
python·django·restful·drf
weixin_421133412 天前
Django 的文档接口
python·django·sqlite
合作小小程序员小小店3 天前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
B站_计算机毕业设计之家4 天前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
茯苓gao4 天前
Django网站开发记录(一)配置Mniconda,Python虚拟环境,配置Django
后端·python·django
码界筑梦坊4 天前
267-基于Django的携程酒店数据分析推荐系统
python·数据分析·django·毕业设计·echarts