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

Django使用ListView调用render后数据库内容不显示如何解决

问题根因

你重写ListView的post方法时,只传入了自定义的asd变量到模板上下文,父类ListView默认生成的drop_down列表数据没有一同传入,导致模板遍历drop_down时拿到空值,后续匹配渲染的逻辑完全无法执行,所以看起来就像数据库没有对应对象。

修复步骤

1. 修正视图的上下文传递逻辑

调用父类的get_context_data()方法获取默认上下文(已经包含你配置的drop_down列表数据),再追加自定义的asd变量即可。同时建议用get_object_or_404替代直接get,避免提交不存在的sourceFile时抛出500错误。
修改后的视图代码:

from django.shortcuts import get_object_or_404

class DropDownList(ListView):
    context_object_name = 'drop_down'
    template_name = "browse.html"
    model = ServiceList

    def post(self, request):
        name = request.POST.get('selected')
        obj = get_object_or_404(ServiceList, sourceFile=name)
        print(obj)
        print(request.POST) # 调试打印
        # 获取父类默认生成的上下文,包含drop_down数据
        context = super().get_context_data()
        # 追加自定义变量
        context['asd'] = obj
        return render(request, self.template_name, context)

2. 修正前端option标签属性

name属性是配置在<select>标签上的,<option>需要用value属性指定提交的值,避免因文本特殊字符导致匹配失败:

{% for obj in drop_down %}
    <option value="{{obj.sourceFile}}">{{obj.sourceFile}}</option>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 03:06:03