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)}")
相关推荐
markfeng84 天前
Python+Django+H5+MySQL项目搭建
python·django
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky5 天前
Django入门笔记
笔记·django
QQ5110082855 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe5 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
B站计算机毕业设计超人5 天前
计算机毕业设计Django+Vue.js高考推荐系统 高考可视化 大数据毕业设计(源码+LW文档+PPT+详细讲解)
大数据·vue.js·hadoop·django·毕业设计·课程设计·推荐算法
计算机程序猿学长5 天前
大数据毕业设计-基于django的音乐网站数据分析管理系统的设计与实现(源码+LW+部署文档+全bao+远程调试+代码讲解等)
大数据·django·课程设计
B站计算机毕业设计超人5 天前
计算机毕业设计Django+Vue.js音乐推荐系统 音乐可视化 大数据毕业设计 (源码+文档+PPT+讲解)
大数据·vue.js·hadoop·python·spark·django·课程设计
B站_计算机毕业设计之家5 天前
电影知识图谱推荐问答系统 | Python Django系统 Neo4j MySQL Echarts 协同过滤 大数据 人工智能 毕业设计源码(建议收藏)✅
人工智能·python·机器学习·django·毕业设计·echarts·知识图谱