在我的表单上,我有两个用于提交表单的按钮。一个按钮删除所选文件(在表格中显示,一个对象复选框),另一个按钮选择它们进行处理。
删除时选择文件时,不需要验证(除了检查至少选择了一个文件)。但是,为了处理,我需要确保只有一个特定扩展名的文件。 基本上,我需要根据用户点击的按钮进行不同的验证过程。
我怎样才能做到最好?我知道我可以在视图中执行验证,但我更倾向于在表单中验证它,因为它更清晰。
以下是相关表格:
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
答案 0 :(得分:4)
关于HTML中按钮的关键要点是只有按下的按钮才会将其数据发送回服务器。因此,您只需检查按钮的data
字段是否使用if form.process_button.data
进行设置,一般情况下就会有效。
在您的特定情况下,由于您的两个按钮都从相同的基础参数名称(action
)中提取数据,因此您需要检查其中一个按钮字段中的数据是否符合预期: / p>
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