簡體   English   中英

Flask-WTForms為IntegerField拋出錯誤而不是驗證失敗

[英]Flask-WTForms throws error for IntegerField instead of failing validation

當我使用wtf_forms和Flask-WTF創建表單並使用IntegerField輸入時,我不能將它與Length驗證器結合使用

如果我刪除長度限制,那么它工作正常。 當然我應該能夠對IntegerField應用長度驗證嗎?

Python代碼。

from flask_wtf import Form
from wtforms import TextField, PasswordField, IntegerField, validators

class RegistrationForm(Form):
    firstname = TextField('First Name', [validators.Required()])
    lastname = TextField('Last Name', [validators.Required()])
    telephone = IntegerField('Telephone', [validators.Length(min=10, max=10, message="Telephone should be 10 digits (no spaces)")])

TypeError
TypeError: object of type 'int' has no len()

Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\index.py", line 45, in submit
if form.validate_on_submit():
File "C:\Python27\lib\site-packages\flask_wtf\form.py", line 156, in validate_on_submit
return self.is_submitted() and self.validate()
File "C:\Python27\lib\site-packages\wtforms\form.py", line 271, in validate
return super(Form, self).validate(extra)
File "C:\Python27\lib\site-packages\wtforms\form.py", line 130, in validate
if not field.validate(self, extra):
File "C:\Python27\lib\site-packages\wtforms\fields\core.py", line 175, in validate
stop_validation = self._run_validation_chain(form, chain)
File "C:\Python27\lib\site-packages\wtforms\fields\core.py", line 195, in _run_validation_chain
validator(form, self)
File "C:\Python27\lib\site-packages\wtforms\validators.py", line 91, in __call__
l = field.data and len(field.data) or 0
TypeError: object of type 'long' has no len()

下面的錯誤意味着您正在嘗試檢查python不允許的整數的長度。 如果要檢查長度,則必須是字符串。 但是,根據定義,IntegerField()是一個整數

object of type 'int' has no len()

你需要創建類似下面的東西。 NumberRange需要一系列數字。

IntegerField('Telephone', [validators.NumberRange(min=0, max=10)])

或者,我建議您使用FormField並定義自己的電話字段。 這里有一個確切的例子來創建一個電話領域:

http://wtforms.simplecodes.com/docs/0.6.1/fields.html#wtforms.fields.FormField

來自http://wtforms.readthedocs.org/en/latest/validators.html#wtforms.validators.Length

“驗證字符串的長度。”

另外我不認為將電話號碼存儲/驗證為整數是個好主意。 您應該使用wtforms.validators.Regexp來驗證數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM