从django的HTML表单中选择字段



我创建了一个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.pyfile

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

相关内容

  • 没有找到相关文章

最新更新