好的,所以我有一个表格,其中取决于下拉列表的值,仅需要填写某些字段,但是我收到了称为“discountpercentage”的键的键错误,因为如果我将其保留为空白,则无处可见cleaned_data,然后当自定义清理尝试运行时,我得到了关键错误,因为它找不到它。
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'的cleaned_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'}
感谢任何能提供帮助的人,它的意义与往常一样!
最佳答案
如您所说,如果未填写该字段,则cleaned_data中不存在该字段。您应该检查密钥是否存在,而不是检查值:
if data['discounton'] == '1' and 'discountitem' not in data: