简体   繁体   中英

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 .

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

If I use print form.category_add.data it tells me it is None

If I use the normal TextField it works fine.

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

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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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