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

Django+HTMX下拉框选中值传递至textarea实现问题

问题分析与修复方案

你的代码存在几个关键问题,导致无法输出预期内容:

1. 缺少result视图的URL路由

按钮的HTMX请求指向{% url 'result' %},但urls.py中未配置该路由,请求无法到达对应视图。

2. test1函数存在两处错误

  • 未导入random模块,调用random.choice()会触发隐性错误
  • 未从请求中获取第三个下拉框的选中值,变量options未定义,也没有从request对象中提取参数

3. 按钮的HTMX请求未包含第三个下拉框的参数

点击按钮时,没有把第三个下拉框(extract_single_city)的选中值传递给后端,导致test1无法获取该值


修复步骤与代码修改

步骤1:补充URL路由(urls.py)

添加result视图的路由:

from django.urls import path
from . import views
urlpatterns = [
    path("", views.trip_selector, name="trips"),
    path("result/", views.result, name="result")  # 新增该行
]

步骤2:修复test1函数(views.py)

导入random模块,并从请求中获取第三个下拉框的选中值:

from django.shortcuts import render
from .models import FullRecord, Country
import random  # 新增导入

# ... 其他代码保持不变 ...

# Create sentence
def test1(request):
    # 获取第三个下拉框的选中值
    selected_city = request.GET.get('extract_single_city', '')
    if not selected_city:
        return ""  # 未选中时返回空或自定义提示文本
    
    sentence_templates = ["The selected trip is ", "Congratulations you have selected the trip ", "You have currently selected travel ", "The currently selected trip is "]
    return f"{random.choice(sentence_templates)} {selected_city}"

# Print in textarea
def result(request):
    test_print_in_result = test1(request)
    return render(request,"result.html", {"test_print_in_result": test_print_in_result})

步骤3:修改按钮的HTMX属性(forms.html)

添加hx-include包含第三个下拉框的参数,确保点击按钮时传递选中值:

<button type="button" class="mybtn" name="btn" 
        hx-get="{% url 'result' %}" 
        hx-swap="outerHTML" 
        hx-target="#id_result" 
        hx-indicator=".htmx-indicator"
        hx-include="[name=extract_single_city]">  <!-- 新增该行 -->
    Button 1
</button>

完成以上修改后,点击按钮时,第三个下拉框的选中值会被传递到test1函数,生成对应句子并渲染到textarea中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:16:12