好的,所以我有一个表单,根据下拉的值,只需要填写某些字段但是我得到一个名为“discountpercentage”的键的键错误,因为如果我把它留空了它的无处可去看到clean_data,然后当自定义清理trys运行时,我得到密钥错误,因为它无法找到它。
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 =='1'打印cleaning_data并且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'}
感谢任何可以提供帮助的人意味着像往常一样!
答案 0 :(得分:0)
如您所说,如果未填写该字段,则clean_data中不存在该字段。您应检查是否存在密钥,而不是检查值:
if data['discounton'] == '1' and 'discountitem' not in data: