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

Django模板遍历表单配送选项不显示问题求助

问题解决方案

核心问题:表单实例未传入模板上下文

你在OrderSummaryView的get方法里创建了Shipping表单实例,但没有将它添加到context字典中,导致模板里的form变量根本不存在,自然无法遍历显示配送选项。

修复步骤

修改views.py中的get方法,把form加入上下文:

def get(self, *args, **kwargs):
    try:
        order = Order.objects.get(user=self.request.user, ordered=False)
        form = Shipping()
        context = {
            'object' : order,
            'couponform': CouponForm(),
            'DISPLAY_COUPON_FORM': True,
            'form': form,  # 新增这一行,将表单实例传入模板
        }
        return render(self.request, 'cart.html', context)
    except ObjectDoesNotExist:
        messages.info(self.request, "You do not have an active order")
        return redirect('estores:home')

额外优化建议

你也可以直接使用Django表单的内置渲染逻辑简化模板代码,避免手动遍历可能出现的错误,比如替换模板中的遍历代码为:

{{ form.shipping_option }}

Django会自动根据你定义的RadioSelect widget生成对应的单选框组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:17:34