Categories

Links

django小提示-FormPreview中的BooleanField

这个问题得确是django的 bug
问题在于django 总是将BooleanField的值处理成True,False,但有个地方存在不一致的地方,就是
CheckboxInput的value_form_datadict方法


代码



  1. def value_from_datadict(self, data, files, name):  

  2.       if name not in data:  

  3.           # A missing value means False because HTML form submission does not  

  4.           # send results for unselected checkboxes.  

  5.           return False  

  6.       return super(CheckboxInput, self).value_from_datadict(data, files, name)  




这个方法会导致一些错误,因为 data是个字符串的词典,因此,这个方法会返回bool的False(当data中没有is_test时)或字符串的'False'(当存在,但值为False时)
第一个是hash 值的计算,一开始的bool类型的False同unicode字符串的False是不同 的. 这样会导致当不核选时需要提交两次
其次是当render的时候,可以查看CheckboxInput的render方法,里面有个check_test,默认被设置为bool,这样,当调用bool('False')时,返回的就是True了


所以,修改上面的方法(或继承新建一个Checkbox2Input),让其根据实际情况返回bool值就ok了
比方说(这只是个quick and dirty的解决方法,英语好的可以提交bug,让django团队来处理这个问题)


代码



  1. def value_from_datadict(self, data, files, name):  

  2.      if name not in data:  

  3.          # A missing value means False because HTML form submission does not  

  4.          # send results for unselected checkboxes.  

  5.          return False  

  6.      #print data[name],"value_form_datadict",type(data[name])  

  7.      result=super(CheckboxInput, self).value_from_datadict(data, files, name)  

  8.      return True if result in ['on','ON','True','true'] else False  



由于存在这两个问题,因此光传入一个check_test lambda 还不足以解决问题,我一开始就以为这个能解决,呵呵

[2007-12-06 11:59:12 | jiangjianxiao]

comments


Powered by Google App Engine