How to make ESIdentityCardNumberField allow blank

164 Views Asked by At

I've got a form to register clients. There I've got one ESIdentityCardNumberField to validate NIF/CIF/NIE, but this form is also considered to allow "Other" country Cards IDs, so I've added another field to get them.

So, I need to override ESIdentityCardNumberField validation to allow blank values if other card id is specified.

How can I get this?

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.")

Thanks in advance.

2

There are 2 best solutions below

0
On

I have noticed bad point of view. Don't use a form field but a validator, like:

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
1
On
ESIdentityCardNumberField(label='DNI/CIF', required=False)