开发者

WTForms doesn't validate - no errors

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 re开发者_StackOverflow中文版ceives 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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜