简体   繁体   English

Python flask WTForms自定义验证-无法从表单获取数据,为“无”

[英]Python flask WTForms custom validation - cant get data from form, is None

I have currently a problem with one of my form fields. 目前,我的一个表单字段存在问题。 The user has to choose or type in a valid category (which is predefined). 用户必须选择或键入有效的类别(预定义)。 To check whether the input is valid I created a custom validation: 为了检查输入是否有效,我创建了一个自定义验证:

class CategoryAddTextField(TextField):
    def process_formdata(self, valuelist):
        if len(valuelist[0].lower().strip()) > 0:
            if valuelist[0].lower().strip() not in cat_list:
                raise ValidationError("Diese Branche existiert nicht")

In cat_list I have all valid options (3300 ~) cat_list is a list . cat_list我具有所有有效的选项( cat_listcat_list是一个list

Here is the inputfield: 这是输入字段:

category_add = CategoryAddTextField(u'Kategorie wählen')

If the input is wrong, everything works fine, the form does not submit and shows the correct error, but if the input is correct, then the form data is not stored. 如果输入错误,则一切正常,表单不会提交并显示正确的错误,但是如果输入正确,则不会存储表单数据。 I tested it and it is None 我测试了它, None

If I use print form.category_add.data it tells me it is None 如果我使用print form.category_add.data告诉我它是None

If I use the normal TextField it works fine. 如果我使用普通的TextField则效果很好。

Okay It seems there is a difference between: 好吧,两者之间似乎有区别:

form.category_add.data

The first version becomes None , while the second one becomes an empty string 第一个版本变成None ,第二个版本变成empty string

request.form["category_add"]

Using the second version fixed my issue: 使用第二个版本解决了我的问题:

class CategoryAddTextField(TextField):
    def process_formdata(self, valuelist):
        if valuelist[0].lower().strip() == "":
            raise ValidationError("Suchen Sie eine Branche aus")
        if len(valuelist[0].lower().strip()) > 0:
            if valuelist[0].lower().strip() not in cat_list:
                raise ValidationError("Diese Branche existiert nicht")

I also added this to make sure that data was entered: 我还添加了此内容以确保输入了数据:

    if valuelist[0].lower().strip() == "":
        raise ValidationError("Suchen Sie eine Branche aus")

In the main.py adding to DB with request.form["category_add"].lower().strip() : 在main.py中使用request.form["category_add"].lower().strip()添加到数据库中:

the_category =  CompanyCategory(category_info=form.category_info.data, category_id_name = request.form["category_add"].lower().strip(), company_id=the_company.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM