Django custom form validation/cleaning

140 Views Asked by At

Okay so I have a form where depending on the value of the drop down only certain fields need to be filled in however im getting a key error for a key called "discountpercentage" because if i leave it blank its no where to be seen insive the cleaned_data and then when the custom clean trys to run i get the key error as it cant find it.

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

And here is what i get if i print the cleaned_data with the discounttype == '1' and discountpercentage left blank.

{'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'}

Thanks to anyone who can help it means a lot like always!

1

There are 1 best solutions below

2
On BEST ANSWER

As you say, if the field is not filled in, it is not present in cleaned_data. Rather than checking for the value, you should check for the existence of the key:

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