好的,所以我有一个表单,根据下拉列表的值,只需要填写某些字段,但是我会收到一个名为"discountpercent"的键的关键错误,因为如果我将其留空,则看不到它对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
如果我打印折扣类型 == '1' 且折扣百分比留空的cleaned_data,这就是我得到的。
{'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: