【发布时间】:2021-06-15 18:23:18
【问题描述】:
我是 Django 新手,我正在开发一个站点,该站点应该从单选按钮获取用户输入并使用所选值进行进一步操作。看到了一些使用Database的方法,但是我想用一种简单的方法直接从模板中获取选中的单选按钮的值。
我正在使用 Django 表单,并且在以 HTML 格式提交表单时收到 UnboundLocalError。它表明在赋值之前引用了局部变量'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]
forms.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>
【问题讨论】:
标签: django django-views django-forms django-templates radio-button