我在使用django表单填写选择选项时遇到问题。即使我定义了选择,我也没有看到任何选择。
我在.py文件中的表单:
class SignupForm(forms.Form):
countrySignup = forms.ChoiceField( required = True,
widget = forms.Select( choices = ('United States', 'Jordan') ))
我的html模板包含以下内容:
<p>
<label for="countrySignup" class="youcountry" data-icon="">Your Country </label> </br>
{{ signupForm.countrySignup }}
{{ signupForm.countrySignup.errors }}
</p>
当然我的视图有以下代码将变量传递给模板:
def myView(request):
#
# create the unbinded forms for registration
#
if request.method == 'GET':
signupForm = regForms.SignupForm()
return render(request,
"login.html",
{'loginForm': loginForm,
'signupForm' : signupForm })
我错过了什么,因为我在选择中看不到任何选项,它仍然是空的
答案 0 :(得分:2)
我错过了文档,选择必须是每个 2个元素的元组列表。
<强> 选择 强>: 2元组的可迭代(例如,列表或元组),用作该字段的选择。此参数接受与模型字段的choices参数相同的格式。有关详细信息,请参阅模型字段参考文档。**
这解决了它:
countrySignup = forms.ChoiceField( choices = [('PS', 'Palestine'),
('JD', 'Jordan')] )