问题
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