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

Django中下拉列表无法从数据库加载数据问题求助

问题排查与修复方案

核心问题:预订页面未加载数据

你访问/booking路径时,对应的bookingview视图没有从数据库查询Court和TimeSlot数据,模板里的{% for %}循环因无数据无法渲染下拉选项。你把数据查询逻辑写在了booked视图的GET分支,但该视图对应/book路径,正常访问预订页面不会触发这个分支。

修复步骤

1. 修改bookingview视图,传递数据到模板

更新views.py中的bookingview,添加数据查询逻辑:

def bookingview(request):
    courts = Court.objects.all()
    time_slots = TimeSlot.objects.all()
    return render(request,"booking/booking.html",{
        "courts": courts,
        "time_slots": time_slots,
    })

2. 修正模板下拉选项的value值

原模板用{{ court }}作为value,传递的是场地名称字符串,但Person模型的court是外键字段,需传递数据库ID才能正确关联。修改booking.html的select部分:

<label for="id_court">Court:</label>
<select id="id_court" name="court" required>
    {% for  court in courts %}
        <option value="{{ court.id }}">{{ court.name }}</option>
    {% endfor %}
</select>

<label for="id_time_slot">Time Slot:</label>
<select id="id_time_slot" name="time_slot" required>
    {% for slot in time_slots %}
        <option value="{{ slot.id }}">{{ slot.time }}</option>
    {% endfor %}
</select>

3. 修复预订提交逻辑(POST请求)

原booked视图的POST分支直接用字符串赋值外键字段会报错,需根据ID查询对应对象再创建Person,同时修正reverse的用法(需传路由name而非函数):

elif request.method == "POST":
    name = request.POST.get('name')
    mobile_number = request.POST.get('mobile_number')
    court_id = request.POST.get('court')
    timeslot_id = request.POST.get('time_slot')
    
    # 获取数据库中的场地和时间段对象
    court = Court.objects.get(id=court_id)
    time_slot = TimeSlot.objects.get(id=timeslot_id)
    
    bookk = Person(
        name=name,
        mobile_number=mobile_number,
        court=court,
        time_slot=time_slot
    )
    bookk.save()
    
    return HttpResponseRedirect(reverse('index'))

完成以上修改后,访问/booking即可看到下拉列表加载出数据库中的场地和时间段数据,提交预订也能正确保存到数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:05:34