0

我有一个表格来注册客户。我有一个 ESIdentityCardNumberField 来验证 NIF/CIF/NIE,但这种形式也被认为允许“其他”国家卡 ID,所以我添加了另一个字段来获取它们。

因此,如果指定了其他卡 ID,我需要覆盖 ESIdentityCardNumberField 验证以允许空白值。

我怎样才能得到这个?

class Client(models.Model):
    name = models.CharField()
    ESCardId = models.CharField(blank=True, null=True)
    otherCardsIds = models.CharField(blank=True, null=True)

class ClientForm(forms.ModelForm):
    ESCardId= ESIdentityCardNumberField()


class ClientAdmin(admin.ModelAdmin):
    form = ClientForm
    fields = ['name', 'ESCardID', 'otherCardsIds']

    def save_model(self, request, obj, form, change):
        if obj.ESCardId is None and obj.otherCardsIds is None:
            raise ValidationError("Enter a spanish cardID or any other.")

提前致谢。

4

2 回答 2

0

我注意到了不好的观点。不要使用表单字段,而是使用验证器,例如:

class ClientForm(forms.ModelForm):

    def clean(self):
        cleaned_data = self.cleaned_data
        CIF = cleaned_data.get('CIF')
        oID = cleaned_data.get('otherCIF')
        if CIF == "" and oID == "":
            raise forms.ValidationError("Introduce one card id")
        if CIF != "" and oID != "":
            raise forms.ValidationError("Introduce ONLY one card id")
        if CIF != "":
            myValidator = ESIdentityCardNumberField()
            myValidator.clean(CIF)

        return cleaned_data
    class Meta:
        model = Client
于 2014-02-23T14:11:42.833 回答
0
ESIdentityCardNumberField(label='DNI/CIF', required=False)
于 2020-08-27T08:56:38.303 回答