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

Django中无法显示media文件夹内数据库存储的PDF文件求助

解决Django中无法从Media文件夹加载PDF并在浏览器显示的问题

关键问题分析与修正步骤

1. 修正URL路径参数格式

urls.py里verPDF的路径参数未指定类型,Django无法正确解析数字ID,需修改为<int:idtermsCondition>:

urlpatterns = [
    path('uploadfile/', views.uploadFile, name="uploadFile"),
    path('verPDF/<int:idtermsCondition>', views.verPDF, name='verPDF'),
]

2. 修复视图里的用户认证判断

verPDF视图中user.is_authenticated()多了括号,is_authenticated是属性而非方法,去掉括号即可:

def verPDF(request, idtermsCondition):
    user = request.user
    if user.is_authenticated:
        if user.is_admin:
            getPDF = termsCondition.objects.get(pk=idtermsCondition)
            return render(request, 'subirTerminos.html', {'termsCondition': getPDF, 'uploadPDF': getPDF.uploadPDF})
        else:
            messages.error(request, '没有权限访问')
    else:
        return redirect('login2')

3. 修正HTML中PDF的访问路径

uploadPDF.url已经包含完整的相对访问路径(比如/media/PDF/xxx.pdf),无需额外拼接media/PDF/,修改iframe的src:

<div>
    <iframe id="verPDF" src="{{ uploadPDF.url }}" 
    style="width:800px; height:800px;"></iframe>
</div>

4. 配置Media文件的访问路由(开发环境)

在项目根urls.py中添加media文件的访问路由,确保开发环境下能正常访问media文件夹:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('uploadfile/', views.uploadFile, name="uploadFile"),
    path('verPDF/<int:idtermsCondition>', views.verPDF, name='verPDF'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. 检查settings.py的Media配置

确保settings.py里正确设置了MEDIA_ROOT和MEDIA_URL:

MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

额外验证步骤

  • 上传PDF后,确认media/PDF文件夹下确实存在该文件
  • 直接在浏览器地址栏输入PDF的完整路径(比如http://localhost:8000/media/PDF/xxx.pdf),确认能正常打开,排除文件本身或权限问题
  • 检查视图中getPDF.uploadPDF是否不为空,避免字段为空导致路径错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:10:51