WTForms does not check - no errors

I had a strange problem with the WTForms library. For tests, I created a form with one field:

class ArticleForm(Form): content = TextField('Content') 

It gets a simple string as content, and now I use form.validate() , and it returns False for any reason.

I looked at the validate() methods of the 'Form and Field object. I found out that the field returns true if the length of the error list is zero. This is true for my test, since I am not getting any errors. In the shell, checking my field returns True as expected.

The validate() method in the Form object simply runs on the fields and calls their validate() method and returns only false if one of the fields is checked as false.

Since my field is checked without errors, I see no reason in the code why form.validate() returns False .

Any ideas?

+6
python wtforms
source share
2 answers

It seems to me that you are simply passing the wrong values ​​to your form. This is what you need to use a form like this:

 from wtforms import Form, TextField # This is wtforms 0.6 class DummyPostData(dict): """ The form wants the getlist method - no problem. """ def getlist(self, key): v = self[key] if not isinstance(v, (list, tuple)): v = [v] return v class ArticleForm(Form): content = TextField('Content') form = ArticleForm(DummyPostData({'content' : 'my content' })) print form.validate() #$ python ./wtf.py #True 

ps: It would be much better if you provided clearer information: code examples and version of WTForms.

+7
source share

What do you pass to the form constructor? You did not specify any context for how the form is used.

The first argument to the form should be a form input shell. Applicable include, but are not limited to:

  • Django ( request.POST or request.GET )
  • Werkzeug ( request.form or request.args )
  • WebOb (dependent: includes Pylon / Pyramid, TurboGears and google appengine webapp framework)
  • cgi.FieldStorage or equivalent

Usage in a view similar to django is as follows:

 def view(request, article_id): article = Article.objects.get(article_id) form = ArticleForm(request.POST, obj=article) if request.POST and form.validate(): # do something # render stuff, etc 
0
source share

All Articles