首页 > 解决方案 > 在 django 中提交单选按钮表单时出现 UnboundLocalError

问题描述

我是 Django 的新手,我正在开发一个站点,该站点应该从单选按钮获取用户输入并使用选定的值进行进一步操作。我见过一些使用数据库的方法,但我想用一种简单的方法直接从模板中获取所选单选按钮的值。

我正在使用 Django 表单,并且在以 HTML 格式提交表单时出现UnboundLocalError 。它显示在 assignment 之前引用了局部变量“selected”。我知道该表格无效,但我不知道为什么请帮助我。

PFA 我的代码。

views.py(仅访问选定单选按钮的值的部分)

def index(request):
    if "GET" == request.method:
        return render(request, 'index.html')
    else:
        excel_file = request.FILES["excel_file"]

        wb = openpyxl.load_workbook(excel_file)

        form = CHOICES(request.POST)

        if form.is_valid():
           selected = form.cleaned_data.get("NUMS")

        else:
           form = CHOICES()


        
        worksheet = wb["Observed"]
        worksheet1 = wb[selected] 

表格.py

from django import forms

NUMS= [
    ('one', 'one'),
    ('two', 'two'),
    ('three', 'three'),
    ('four', 'four'),
    ('five', 'five')

    ]
class CHOICES(forms.Form):
    NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=NUMS)

index.html(仅单选按钮的一部分)

<form action="index" method="POST">
                    {% csrf_token %}
                    {{form.NUMS}}
                    
                    <input type="radio" id="NUMS" name="NUMS" value="1 Day Lead">
                    <label for="NUMS">1 Day Lead</label>
                    <input type="radio" id="NUMS" name="NUMS" value="2 Day Lead">
                    <label for="NUMS">2 Days Lead</label>
                    <input type="radio" id="NUMS" name="NUMS" value="3 Day Lead" checked>
                    <label for="NUMS">3 Days Lead</label>
                    <input type="radio" id="NUMS" name="NUMS" value="4 Day Lead">
                    <label for="NUMS">4 Days Lead</label>
                    <input type="radio" id="NUMS" name="NUMS" value="5 Day Lead">
                    <label for="NUMS">5 Days Lead</label>
                    
                    
                </form>

标签: djangodjango-viewsdjango-formsdjango-templatesradio-button

解决方案


您的表单数据似乎无效,因此selected从未定义该变量。但是,您尝试在下面几行返回它。您也许可以通过添加默认值来解决此问题,selected以便它始终存在:

selected = None 
if form.is_valid():
   selected = form.cleaned_data.get("NUMS")
else:
   form = CHOICES()

worksheet = wb["Observed"]
worksheet1 = wb[selected] 

推荐阅读