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

Django模板未渲染为HTML而是在浏览器显示为普通文本该如何解决

问题原因

你调用render()函数时传参错误导致响应头异常。Django的render()函数参数定义为:
render(request, template_name, context=None, content_type=None, status=None, using=None)
你给render()传了4个位置参数,第4个位置参数对应的是content_type响应头字段,你把存储Profilepix的字典传到了这个位置,导致响应的Content-Type被设置为错误值,浏览器识别到非text/html的内容类型,就会把页面内容当成普通文本展示,不会渲染为HTML页面。

修复方案

把两个上下文数据合并为同一个字典后再传给render()的第三个参数即可,修改后的代码如下:

@login_required
def product_list(request, template_name='product/product_list.html'):
    ppix = Profilepix.objects.filter(user=request.user)
    product = Product.objects.filter(username=request.user).order_by('-postdate')
    data = {}
    data['object_list'] = product
    # 合并上下文数据
    data['Profilepix'] = ppix
    return render(request, template_name, data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:39:03