WTForms doesn't validate - no errors

岁酱吖の 提交于 2019-12-07 00:43:56

问题


I got a strange problem with the WTForms library. For tests I created a form with a single field:

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

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

I looked into the validate() methods of the 'Form and Field object. I found out that the field returns true if the length of the errorlist is zero. This is true for my test as i don't get any errors. In the shell the validation of my field returns True as expected.

The validate() methode in the Form object just runs over the fields and calls their validate() method and only returns false if one of the fields is validated as false.

So as my Field is validated without any error i can't see any reason in the code why form.validate() returns False.

Any ideas?


回答1:


It seems to me, you just pass wrong values to your form. This is what you need to use such form:

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 gave more explicit information: code examples and version of WTForms.




回答2:


What are you passing to the form's constructor? You didn't provide any context on how the form is used.

The first argument to a form must be a form-data input wrapper. Valid ones include, but are not limited to:

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

Use in a django-like view looks like:

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


来源:https://stackoverflow.com/questions/4534115/wtforms-doesnt-validate-no-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!