根据单击的按钮验证WTForm表单

发布于 2021-01-29 16:51:43

在我的表单上,我有两个用于提交表单的按钮。一个按钮删除选定的文件(显示在表中,一个复选框显示在一个对象上),另一个按钮选择它们进行处理。

在删除时选择文件时,无需进行验证(除了检查是否已选择至少一个文件外)。但是,为了进行处理,我需要确保确实存在一个具有特定扩展名的文件。
基本上,我需要基于用户单击哪个按钮的不同验证过程。

我怎样才能最好地做到这一点?我知道我可以在视图中执行验证,但是我更喜欢在表单中进行验证,因为它更干净。

这是有问题的表格:

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
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    有关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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看