【问题标题】:Django custom form validation/cleaningDjango 自定义表单验证/清理
【发布时间】:2023-04-05 03:38:02
【问题描述】:

好的,所以我有一个表单,根据下拉列表的值,只需要填写某些字段,但是我得到一个名为“折扣百分比”的键的键错误,因为如果我将其留空,它就没有位置看到了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' 且 discountpercentage 留空的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'}

感谢任何可以提供帮助的人,这意味着一如既往!

【问题讨论】:

    标签: python django forms error-handling cleaned-data


    【解决方案1】:

    如您所说,如果该字段未填写,则它不存在于cleaned_data中。与其检查值,不如检查键是否存在:

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

    【讨论】:

    • 感谢工作!奇怪的是它在现在之前起作用了,显然我需要让它们都不需要,所以我的自定义清洁可以接管我理解的,但这从未发生过。但无论哪种方式,它的工作,所以非常感谢你!
    • 我实际上设法修复了它并将它恢复到之前的状态,因为当我查看您的修复程序时,它向我展示了我所做的更改。我需要字段为 required=False ,然后我的干净方法如何完美运行:) 再次感谢。
    猜你喜欢
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2018-02-08
    • 2021-06-22
    • 2011-05-04
    • 1970-01-01
    相关资源
    最近更新 更多