3
If I define
cpf = models.CharField(max_length=11, unique=True, null=True, blank=True)
It turns out that if I leave a record with the null value, when I try to save a second record, it accuses duplicate value.
How to get around this situation?
3
If I define
cpf = models.CharField(max_length=11, unique=True, null=True, blank=True)
It turns out that if I leave a record with the null value, when I try to save a second record, it accuses duplicate value.
How to get around this situation?
1
If you define unique=True means that you cannot repeat any value, even . The solution to this problem is to make a check before saving, if any repeated returns error to the users.NULL
In the forms.py you can do a check the following way:
class SeuModelForm(forms.ModelForm):
class Meta():
model = SeuModel
def __init__(self, *args, **kwargs):
super(SeuModelForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.id = kwargs['instance'].id
else:
self.id = None
def clean(self):
cleaned_data = super(SeuModelForm, self).clean()
cpf = cleaned_data.get('cpf')
if cpf:
try:
SeuModel.objects.exclude(id=self.id).get(cpf=cpf)
except (SeuModel.DoesNotExist):
pass
else:
self.add_error('cpf', u'Este CPF já foi cadastrado')
After doing a survey I found that the problem was not with Django, so the bank accepts yes more than one NULL. To solve this problem more simply, just return None if the field has not been completed.
class SeuModelForm(forms.ModelForm):
class Meta():
model = SeuModel
def clean_cpf(self):
return self.cleaned_data['cpf'] or None
Or better yet, directly in the method save() of the model:
def save(self, *args, **kwargs):
if not self.cpf:
self.cpf = None
super(SeuModel, self).save(*args, **kwargs)
I liked all solutions, I used the second. But it means that the first checks duplicities and informs the user? I liked.
Yes, the first one checks if you have any registration using the informed CPF, if there it returns the error.
Browser other questions tagged django
You are not signed in. Login or sign up in order to post.
Which DBMS is using?
– Math
@Math I am using Sqlite in dev and will use Postgresql in production.
– Regis Santos