我有一张注册客户的表格。在那里我有一个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.")
提前致谢。
答案 0 :(得分: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
答案 1 :(得分:0)
ESIdentityCardNumberField(label='DNI/CIF', required=False)