【问题标题】:Save fields even if I have a ValidationError即使我有 ValidationError 也保存字段
【发布时间】:2017-08-01 12:21:14
【问题描述】:

在我的forms.py 文件中,我有一个给我带来大问题的类:

class CustomerBaseForm(forms.Form):
   ...

    def clean(self):
        cleaned_data = super(CustomerBaseForm, self).clean()
        bank_account = cleaned_data.get("bank_account")
        ssn = self.cleaned_data.get('ssn')
        bank = self.cleaned_data.get('bank')
        bank_transit = self.cleaned_data.get('bank_transit')

        v = CustomerProfileFormCleaner(self)
        v.clean()

        # The concatenation of bank transit, the bank account and the bank
        # number must be unique. Hence, the following message would be
        # displayed if it is already in use.
        msg = _('The bank, the bank transit and the bank account are already in use')

        customer = CustomerProfile.objects.filter(ssn=ssn)
        qs = FinancialProfile.objects.filter(
            bank=bank,
            bank_transit=bank_transit,
            bank_account=bank_account)

        if customer.count() == 1:
            qs = qs.exclude(customer_id__in=[cust.id for cust in customer])
        if qs.count() > 0:
            self.add_error('bank_account', msg)
            self.add_error('bank', '')
            self.add_error('bank_transit', '')

即使我有ValidationErrorforms.Form,我如何保存bankbank_transitbank_account 字段?如果ValidationError 阻止我保存字段,我认为可以强制保存它们。如果没有,是否有解决方法可以做到这一点?

我以为我可以在课堂上做这样的事情,但不清楚..

class Meta:
     model = FinancialProfile
     exclude = ['bank', 'bank_transit', 'bank_account']

【问题讨论】:

    标签: django forms unit-testing


    【解决方案1】:

    如果您即使遇到运行时错误也尝试执行操作,您可以将可能引发ValidationError 的代码封装在try-except 结构中。我链接的页面是它的官方文档,但这里是简短版本。您将可能失败的代码放在代码的try: 部分。然后,在它之后你可以放置它可能抛出的异常。这将防止程序崩溃,然后在except: 中您可以告诉您的程序如何处理它。

    例如

    try:
        perform_function(my_dict[my_key])
    except KeyError:
        print("I'm sorry the function could not be performed")
    #rest of the program.....
    

    在上面的示例中,我们将字典的元素传递给perform_function。如果我们不将其包装在 try-except 结构中,那么如果my_dict 不包含my_key,我们的程序就会崩溃。但是,现在它不会崩溃,它会向用户打印错误消息,并将继续它必须做的任何其他事情。所以,在你的情况下,你会做这样的事情:

    try:
        #part of the program that could throw ValidationError
    except ValidationError:
        #Save fields
    #continue on with program
    

    希望这可以帮助您开始解决问题。我强烈建议阅读我链接的那个页面,它比我在这里更深入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2015-03-05
      • 1970-01-01
      • 2013-06-22
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多