2017-03-09 9 views
0

我目前有一個表單域的問題。用戶必須選擇或輸入有效的類別(這是預定義的)。檢查輸入是否有效我創建了一個自定義的驗證:Python燒瓶WTForms自定義驗證 - 無法從窗體中獲取數據,是無

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") 

cat_list我有所有有效的選項(3300〜)cat_listlist

這裏是inputfield:

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

如果輸入錯誤,一切正常,形式不提交,並顯示正確的錯誤,但如果輸入是正確的,那麼表單數據不存儲。我測試了它,它是None

如果我使用print form.category_add.data它告訴我,這是None

如果我使用普通TextField它工作正常。

回答

0

好吧似乎有之間的差異:

form.category_add.data 

第一個版本成爲None,而第二個成爲empty string

request.form["category_add"] 

使用第二版本的固定我的問題:

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") 

我也加了這個以確保臨時t的數據被輸入:

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

在main.py添加到DB與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)