request.vars.variablename gives empty string instead of None

雨燕双飞 提交于 2019-12-25 07:24:31

问题


I am using SQLFORM.factory to create a custom form. In this form I have a field as:
Field('useraccount','unicode',default=None)
So as per my understanding, when user does not supply this value, request.vars.useraccount will be None. But it rather shows empty string value. I can convert it to None by checking for empty string value but I do not want to do that. Please suggest me any solution.


回答1:


When the form is submitted, if the "useraccount" input field is empty, the browser still sends an empty string for that field, so that is what goes into request.vars.useraccount. Since an empty string is a valid value for a string field, web2py does not override that and convert it to None -- if you want it to be converted, you must do so explicitly. One option is to create a custom validator that converts empty strings to None.

def empty_to_none(value):
    return (None if value == '' else value, None)

SQLFORM.factory(Field('useraccount', 'unicode', requires=empty_to_none))

A validator must be a callable that takes a value and returns a tuple including a value (the original value or possibly a transformed version of it, as in this case) and either None (if there is no error) or an error message. The above validator is simple enough that it could easily be moved to a lambda:

SQLFORM.factory(Field('useraccount', 'unicode',
                      requires=lambda v: (None if v == '' else v, None)))

Also, note that setting the default value in SQLFORM.factory is only useful for pre-populating the form fields (and in this case, you are not pre-populating with anything). The only other use of the default attribute is for database inserts, but since this Field object is not part of a DAL table model, it won't be used for inserts anyway.



来源:https://stackoverflow.com/questions/18636247/request-vars-variablename-gives-empty-string-instead-of-none

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