我正在尝试使用flask和flask-wtf构建一个简单的webform。
在我的表单中,我要求所需的分段类型(选项:通用,自动和自定义)。如果类型是自定义的,我需要获得具有规范的特殊字段。
以下是我的代码。它很有用,但我觉得它很难读。
在forms.py
中from flask_wtf import Form
from wtforms import StringField, RadioField, BooleanField, TextAreaField
from wtforms import validators
class requestSettings(Form):
typeOfSegmentation = RadioField('typeOfSegment',
choices=[('generic', 'by generic persona'), \
('auto', 'by automatic clustering'),
('custom', 'by manual definition')
],
default='generic',
validators=[validators.DataRequired("indicate the method to segment users")])
typeOfSegmentation_custom = TextAreaField('custom definition')
def validate(self):
is_validated = True
rv = Form.validate(self)
if not rv:
is_validated = False
if self.typeOfSegmentation.data == 'custom':
if not self.typeOfSegmentation_custom.data:
self.typeOfSegmentation_custom.errors.append("Please specify the way you define your segments")
is_validated = False
return is_validated
在我的HTML
中<!DOCTYPE html>
<html>
<head>
</head>
<body>
Your request is {{ session_id }} <br>
{% for field, errors in form.errors.items() %}
{% for error in errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
{% endfor %}<br>
{% block content %}
<h1>Segmentation</h1>
<form action="" method="post" name="name">
<p>Select the method to segment user:
<table>
<tr>
{% for subfield in form.typeOfSegmentation %}
<tr>
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>
{% if loop.index0 == 2 %}
<td > Enter manual description {{form.typeOfSegmentation_custom}}
</td>
{% endif %}
</tr>
{% endfor %}
</table>
</form>
{% endblock %}
</body>
</html>
这是正确的方法吗?烧瓶WTF中是否存在radiobuttons +文本字段?