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

Django中ComboBox选择项无法在TextArea输出问题求助

修正后的代码实现

forms.py

from django import forms

# 定义下拉选择的颜色选项
COLOR_CHOICES = [
    ('red', 'Red'),
    ('blue', 'Blue'),
    ('green', 'Green'),
]

class ColorChoiceForm(forms.Form):
    # 下拉选择字段
    color = forms.ChoiceField(choices=COLOR_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}))
    # 结果显示文本域,设置为只读
    result = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'readonly': 'readonly', 'rows': 3}))

views.py

from django.shortcuts import render
from .forms import ColorChoiceForm

def home(request):
    result_text = ""
    # 根据请求方式初始化表单,POST请求时携带提交数据
    form = ColorChoiceForm(request.POST or None)
    
    if request.method == 'POST' and form.is_valid():
        selected_color = form.cleaned_data.get('color')
        # 颜色判断逻辑
        if selected_color == 'red':
            result_text = "You chose red"
        elif selected_color == 'blue':
            result_text = "You chose blue"
        elif selected_color == 'green':
            result_text = "You chose green"
        # 将结果填充到文本域的初始值中
        form.fields['result'].initial = result_text
    
    return render(request, 'home.html', {'form': form})

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Color Selector</title>
    <style>
        .container { width: 50%; margin: 2rem auto; }
        .form-group { margin-bottom: 1.5rem; }
        label { display: block; margin-bottom: 0.5rem; font-weight: 500; }
        select, textarea { width: 100%; padding: 0.6rem; border: 1px solid #ddd; border-radius: 4px; font-size: 1rem; }
        button { padding: 0.6rem 1.2rem; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Choose a Color</h2>
        <!-- 表单设置POST提交方式,必须包含CSRF令牌 -->
        <form method="post">
            {% csrf_token %}
            <div class="form-group">
                {{ form.color.label_tag }}
                {{ form.color }}
            </div>
            <div class="form-group">
                {{ form.result.label_tag }}
                {{ form.result }}
            </div>
            <button type="submit">Submit</button>
        </form>
    </div>
</body>
</html>
关键修正说明
  • 表单添加{% csrf_token %}:Django默认拦截未携带CSRF令牌的POST请求,这是提交无响应的核心原因
  • 视图兼容GET/POST请求:通过request.POST or None初始化表单,POST请求时验证数据并执行颜色判断逻辑
  • 结果文本域设为只读:避免用户手动修改输出内容,同时将处理后的文本填充回表单字段展示
  • 表单类规范定义:明确选择项和字段属性,确保页面渲染出正确的交互控件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:30:14