我创建了一个HTML表单来注册用户,但是我有一个性别字段的问题:
<form action="" method="POST">
{% csrf_token %}
<select name="gender">
<option hidden>Gender</option>
<option value="0">Male</option>
<option value="1">Female</option>
<option value="2">Prefer not to say</option>
</select>
</form>
myforms.py
file
class RegisterForm(forms.Form):
GENDER = [
("0", "Male"),
("1", "Female"),
("2", "Other")
]
gender = forms.ChoiceField(choices=GENDER)
我试图在下面的视图中获得有效的数据:
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
return HttpResponse("hello")
我不能给is_valid()
这部分的html
- my view is class-based.
我尝试没有<select>
和{{ form.gender }}
,它工作了,但当我在HTML中使用<select>
时,它不起作用。
您需要添加字段小部件:forms.py
class RegisterForm(forms.Form):
GENDER = [
("0", "Male"),
("1", "Female"),
("2", "Other")
]
gender = forms.ChoiceField(label='Gender' ,widget=forms.RadioSelect(choices=GENDER)) # new