Django自定义表单验证/清除

问题描述:

好吧,我有一个表格,其中取决于下拉的值只有某些领域需要填写,但即时获得一个关键的错误称为“discountpercentage”,因为如果我离开它空白它没有在哪里看到insive clean_data,然后当自定义清理trys运行我得到的关键错误,因为它无法找到它。Django自定义表单验证/清除

def clean(self): 
    data = self.cleaned_data 
    print(str(data)) 
    #try: 
    # if data['discountcode']: 
    #  code = data['discountcode'] 
    #  try: 
    #   DiscountCode.objects.filter(discountcode=code) 
    #   self._errors["discountcode"] = ErrorList([u"Discount code must be unique."]) 
    #  except: 
    #   pass 
    #except: 
    # pass 

    if data['discounton'] == '1' and not data['discountitem']: 
     self._errors["discounton"] = ErrorList([u"Please select items to apply discount on."]) 
    elif data['discounton'] == '2' and not data['discountcategory']: 
     self._errors["discounton"] = ErrorList([u"Please select category to apply discount on."]) 
    elif data['discounton'] == '3': 
     pass 



    if data['discounttype'] == '1' and not data['discountpercentage']: 
     self._errors["discounttype"] = ErrorList([u"Please provide a percentage to discount."]) 
    elif data['discounttype'] == '2' and not data['discountvalue']: 
     self._errors["discounttype"] = ErrorList([u"Please provide a value to discount."]) 


    if data['discountexpiry'] == '1' and not data['discountexpiryuse']: 
     self._errors["discountexpiry"] = ErrorList([u"Please provide a redeem limit."]) 
    elif data['discountexpiry'] == '2' and not data['discountexpirydate']: 
     self._errors["discountexpiry"] = ErrorList([u"Please provide a date disable this discount code."]) 
    elif data['discountexpiry'] == '3': 
     pass 
    return data 

这里是我所得到的,如果我与discounttype打印cleaned_data ==“1”和discountpercentage留空。

{'uselimit': u'3', 'discounton': u'1', 'discountcode': u'uyhgkjhg', 'mincarttotal': u'3', 'discountstart': u'2014-02-19', 'marketid': None, 'discountitem': [], 'uses': None, 'discountcategory': [], 'owner': None, 'discounttype': u'1', 'discountexpiry': u'3'} 

感谢任何能够帮助它的人,这意味着我们永远都是这样!

正如你所说,如果该字段没有填写,它不存在于cleared_data中。而不是检查价值,你应该检查密钥的存在:

if data['discounton'] == '1' and 'discountitem' not in data: 
+0

谢谢你的工作!奇怪的是,它现在是纯粹的工作,我需要使他们的领域都不需要,所以我的自定义清理可以接管我了解,但这从来没有发生过。但无论哪种方式,它的工作非常感谢你! –

+0

我实际上设法解决它,并返回它之前的情况,因为当我看着你的修复程序时,它向我展示了我改变了什么。我需要的字段是必需的=假,然后我的干净的方法是如何完美的:)再次感谢。 –