所以我在Web2py中写了一个函数,在条件下在数据库中的表中创建一条记录,但Web2py创建记录,尽管该条件未满足,
这是函数
def buy_product():
price = price_set(db,auth,'product')
balance = limit(db,auth,'settings','account_balance')
if balance !=None:
if balance < price:
form=redirect(URL('order'))
else:
form=crud.create(db.letter)
if form.accepts(request.vars, session):
tax = float(postage(form.vars.tax_type).replace("-","."))
##########################
# I'm talking about this #
##########################
if balance < (price + tax):
response.flash='You don\'t have enough balance to buy this product'
redirect(URL('not_processed'))
else:
function_1(....)
...
...
update_field(db,auth,'settings','account_balance',-price)
response.flash='Done'
redirect(URL('products'))
pass
elif form.errors:
response.flash='Error 01'
else:
pass
###############################
else:
form=redirect(URL('settings'))
return dict(form=form)
这就是当 Balance < price + tax
用户应该被重定向到not_processed
无需在数据库中创建新记录。
但是 web2py 将用户重定向到 not_processed
并使用用户输入的信息创建记录,而不执行此部分。所以用户看到他买了一些东西,但它还没有处理(见下文)
function_1(....)
...
...
update_field(db,auth,'settings','account_balance',-price)
response.flash='Done'
redirect(URL('products'))
pass
有什么想法吗?
谢谢
最佳答案
Crud 在内部管理插入/更新,并且不使用 form.accepts。
您有两个选择:
1 - 使用 SQLFORM
form=SQLFORM(db.letter)
if form.accepts(request.vars, session):
tax = float(postage(form.vars.tax_type).replace("-","."))
##########################
# I'm talking about this #
##########################
2 - 使用 CRUD 事件
def myfunction(form):
# do your stuff here
# it will be called only when form is accepted
def myotherfunction(form):
if form.errors:
#do something here in case of errors
#it will be called during the form validation
crud.settings.create_onvalidation = myotherfunction
crud.settings.create_onaccept = myfunction
#the above can be:
#crud.create_onaccept = lambda form: myfunction(form)
# define the above events before the creation of the form
form=crud.create(db.letter)
请注意,SQLFORM 与 crud 有点不同,SQLFORM 期望您在 form.accepts 方法中验证表单,而 crud 在内部执行此操作并使用事件作为 onvalidation、onaccept 进行自定义验证。
关于python - 通过未填充条件创建的 Web2py CRUD.read() 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000602/