即使我有ValidationError,也保存字段

时间:2017-08-01 12:21:14

标签: django forms unit-testing

在我的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', '')

即使我有bankbank_transit,我怎么能保存字段bank_accountValidationErrorforms.Form?如果ValidationError阻止我保存字段,我认为可以强制保存它们。如果没有,是否存在解决方法?

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

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

1 个答案:

答案 0 :(得分:0)

如果您即使遇到运行时错误也尝试执行操作,则可以将可能引发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

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