Pla*_*sma 3 python flask wtforms flask-wtforms
在我的表单上,我有两个按钮用于提交表单。一个按钮删除选定的文件(显示在表格中,一个复选框用于对象),另一个按钮选择它们进行处理。
当文件在删除时被选择时,不需要验证(除了检查是否至少选择了一个文件)。但是,为了进行处理,我需要确保只有一个具有特定扩展名的文件。基本上,我需要根据用户单击的按钮进行不同的验证过程。
我怎样才能最好地做到这一点?我知道我可以在视图中执行验证,但我更喜欢在表单内验证它,因为它更干净。
这是有问题的表格:
class ButtonWidget(object):
"""A widget to conveniently display buttons.
"""
def __call__(self, field, **kwargs):
if field.name is not None:
kwargs.setdefault('name', field.name)
if field.value is not None:
kwargs.setdefault('value', field.value)
kwargs.setdefault('type', "submit")
return HTMLString('<button %s>%s</button>' % (
html_params(**kwargs),
escape(field._value())
))
class ButtonField(Field):
"""A field to conveniently use buttons in flask forms.
"""
widget = ButtonWidget()
def __init__(self, text=None, name=None, value=None, **kwargs):
super(ButtonField, self).__init__(**kwargs)
self.text = text
self.value = value
if name is not None:
self.name = name
def _value(self):
return str(self.text)
class MultiCheckboxField(SelectMultipleField):
"""
A multiple-select, except displays a list of checkboxes.
Iterating the field will produce subfields, allowing custom rendering of
the enclosed checkbox fields.
"""
widget = ListWidget(prefix_label=False)
option_widget = CheckboxInput()
class ProcessForm(Form, HiddenSubmitted):
"""
Allows the user to select which objects should be
processed/deleted/whatever.
"""
PROCESS = "0"
DELETE = "-1"
files = MultiCheckboxField("Select", coerce=int, validators=[
Required()
]) # This is the list of the files available for selection
process_button = ButtonField("Process", name="action", value=PROCESS)
delete_button = ButtonField("Delete", name="action", value=DELETE)
def validate_files(form, field):
# How do I check which button was clicked here?
pass
Run Code Online (Sandbox Code Playgroud)
关于 HTML 中的按钮要注意的关键是只有被按下的按钮将其数据发送回服务器。所以你可以只检查按钮的data字段是否设置使用if form.process_button.data东西将在一般情况下工作。
在您的特定情况下,由于您的两个按钮都从相同的基础参数名称 ( action) 中提取数据,因此您需要检查其中一个按钮字段中的数据是否符合您的预期:
def validate_files(form, field):
# If the ButtonFields used different names then this would just be
# if form.process_button.data:
if form.process_button.data == ProcessForm.PROCESS:
# Then the user clicked process_button
else:
# The user clicked delete_button
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5159 次 |
| 最近记录: |