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

HTMX+Django级联下拉框:第二个联动HTMX请求未触发

问题解决:第二个下拉框无法触发HTMX请求更新第三个下拉框

核心原因是:第一个下拉框更新第二个下拉框时,新渲染的delivery_location下拉框丢失了HTMX属性,导致选中时无法触发请求。以下是具体修复方案:

1. 修复局部模板oc_update_local.html

当第一个下拉框触发更新后,你替换了#div_local的内容,但新生成的delivery_location下拉框没有带上hx-get、hx-trigger等关键属性,所以无法触发后续请求。

方案A:复用表单字段(推荐)

修改oc_update_local视图,重新构建带有HTMX属性的delivery_location字段:

from django import forms
from django.urls import reverse_lazy

def oc_update_local(request):
    company = request.GET.get('purchased_by')
    empresa = OurCompany.objects.get(pk=company)
    if empresa.definecat == 1:
        if empresa.name[:5] == "Cabiu":
            company = OurCompany.objects.get(name='Cabiunas Inc')
            empreendimentos = Empreendimento.objects.filter(company=company).order_by('name')
        elif empresa.name[:5] == "Coque":
            company = OurCompany.objects.get(name='Coqueiral Agropecuaria Matriz')
            empreendimentos = Empreendimento.objects.filter(company=company).order_by('name')
    else:
        empreendimentos = Empreendimento.objects.filter(company=company).order_by('name')
    
    # 重新构建带HTMX属性的delivery_location字段
    delivery_location_field = forms.ModelChoiceField(
        label="Local de Entrega/Obra",
        queryset=empreendimentos,
        widget=forms.Select(attrs={
            'class': 'form-control',
            'hx-get': reverse_lazy('compras:oc_update_cc'),
            'hx-trigger': 'change',
            'hx-target': '#div_cc',
            'hx-swap': 'outerHTML'
        })
    )
    return render(request, "compras/partials/oc_update_local.html", {
        "delivery_location_field": delivery_location_field
    })

然后在oc_update_local.html中用crispy渲染这个字段:

{% load crispy_forms_tags %}
{{ delivery_location_field | as_crispy_field }}

方案B:手动添加HTMX属性

如果不想修改视图,直接在局部模板的select标签中手动写入HTMX属性:

{% load crispy_forms_tags %}
<div class="form-group col-4">
    <label for="id_delivery_location">Local de Entrega/Obra</label>
    <select name="delivery_location" id="id_delivery_location" class="form-control"
            hx-get="{% url 'compras:oc_update_cc' %}"
            hx-trigger="change"
            hx-target="#div_cc"
            hx-swap="outerHTML">
        {% for emp in empreendimentos %}
            <option value="{{ emp.pk }}">{{ emp.name }}</option>
        {% endfor %}
    </select>
</div>

2. 验证请求参数匹配

确保oc_update_cc视图中获取的参数名与select的name属性一致:
视图中用request.GET.get('delivery_location'),所以局部模板里的select必须设置name="delivery_location",否则视图无法拿到选中的值。

3. 调试验证

打开浏览器开发者工具(F12):

  • 切换到Network标签,选择第二个下拉框,检查是否有HTMX请求发出
  • 如果有请求但返回错误,检查CentroCusto.objects.filter(imovel=local)的逻辑:确认imovel字段是关联Empreendimento的外键,且local是正确的主键值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:37:12