2011-11-03 86 views
1

因此,我worte Web2py中的功能创建一个条件下的数据库中的表中的记录,但Web2py创建记录allthough条件未填充,Web2py CRUD.read()记录虽然没有填充条件创建

这里是它的sepposed功能

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 

任何想法?

谢谢

回答

3

管理界面污物的插入/更新内部,它不使用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是污物的有点不同,SQLFORM希望你验证在form.accepts方法的形式,而污物确实它在内部,并使用事件onvalidation,onaccept定制验证。

+0

你应该也可以这样做: ''form = crud.create(db.letter,onvalidation = myvalidationfunction)'' SQLFORM和crud都接受失效参数。我相信,你可以检查额外的条件,如果这些条件不使用''form.errors.field =“不能做”'' 我只提到它,因为你可能不希望对所有单个onvalidation功能满足添加错误CRUD,你可以有一个很好的理由使用CRUD超过SQLFORM(SQLFORM还接受onvalidation参数)。 见:http://web2py.com/books/default/chapter/29/7#onvalidation 更多 – Kasapo