0
When I wish to register a new user in Django, I receive the following warning:
UNIQUE constraint failed: polls_usuario.matriculaUsuario
What might be going on?
py views.
def registrar(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
usuario_form = UsuarioForm(request.POST)
if form.is_valid() and usuario_form.is_valid():
user = form.save(commit=False)
user.refresh_from_db() # load the profile instance created by the signal
user.usuario.matriculaUsuario = form.cleaned_data.get('matriculaUsuario')
usuario_form.save()
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request,user)
return render(request, 'polls/index.html', user)
#return HttpResponseRedirect(reverse('/'))
#return redirect('/')
else:
form = SignUpForm()
usuario_form = UsuarioForm()
return render(request, 'polls/registrar.html', {'form': form , 'usuario_form':usuario_form})
Forms.py
class UsuarioForm(forms.ModelForm):
class Meta:
model = Usuario
fields = ('matriculaUsuario',)
class SignUpForm(UserCreationForm):
first_name = forms.CharField(label='Primeiro Nome',max_length=30, required=False, help_text='Opcional.')
last_name = forms.CharField(label='Último Nome',max_length=30, required=False, help_text='Opcional.')
email = forms.EmailField(label='E-mail',max_length=254, help_text='Informe o seu e-mail (Requerido)')
username = forms.CharField(label='Nome de usuário', min_length=4, max_length=150)
password1 = forms.CharField(label='Senha', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmação da senha', widget=forms.PasswordInput)
matriculaUsuario = forms.CharField(label='Matrícula',max_length=12,validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])
class Meta:
model = User
fields = ['first_name', 'last_name','username','matriculaUsuario','email','password1', 'password2',]
def clean_username(self):
username = self.cleaned_data['username'].lower()
r = User.objects.filter(username=username)
if r.count():
raise ValidationError("Nome de usuário já cadastrado")
return username
def clean_email(self):
email = self.cleaned_data['email'].lower()
r = User.objects.filter(email=email)
if r.count():
raise ValidationError("E-mail já cadastrado")
return email
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError("Senhas não conferem")
return password2
def save(self, commit=True):
user = User.objects.create_user(
self.cleaned_data['username'],
self.cleaned_data['email'],
self.cleaned_data['password1']
)
return user
class EditProfileForm(forms.ModelForm):
first_name = forms.CharField(label='Nome')
last_name = forms.CharField(label='Sobrenome')
username = forms.CharField(min_length=4, max_length=150,help_text=("Insira um novo nome de usuário"), label='Nome de usuário')
email = forms.EmailField(label='E-mail')
matriculaUsuario = forms.CharField(label='Matrícula', max_length=12,validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])
class Meta:
model = User
fields = ['first_name', 'last_name','username','matriculaUsuario','email']
py.models
class Usuario(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
matriculaUsuario = models.CharField(default='000000000000',max_length=12,primary_key=True,null=False,help_text=_('São requeridos os 12 dígitos referentes à sua matrícula'), validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def update_user_usuario(sender, instance, created, **kwargs):
if created:
Usuario.objects.create(user=instance)
instance.usuario.save()
@receiver(post_save, sender=User)
def create_user_usuario(sender, instance, created, **kwargs):
if created:
Usuario.objects.create(user=instance)
post_save.connect(create_user_usuario,sender=User)
@receiver(post_save, sender=User)
def save_user_usuario(sender, instance, created,**kwargs):
if created:
instance.usuario.save()
EDIT
The message says that you are trying to include a "repeated" record, in a table whose field
matriculaUsuario
has the restrictionUNIQUE
, translating: you are trying to register a second student with the same number of enrollment as one that already exists in the table, with restriction for that.– Sidon
@Sidon, in case the registration is to be unique among users. What should I do to avoid this error? Because there is only the admin user in the bank and your registration is not the same that is being registered as test.
– Murilo de Jesus
You need to check before calling the
save()
, I suggest testing the Django shell to make sure it is sending the data correctly.– Sidon
@Sidon, the POST output was: first_name 'Test last_name 'Test username 'test matriculaUsuario '222222222222' email '[email protected]' password1 'RSRSRSRS'
 password2 'RSRSRSRS'
– Murilo de Jesus
Log in to the Django admin and try to register some users there to see what happens.
– Sidon
@Sidon, the same mistake happens
– Murilo de Jesus
Let’s go continue this discussion in chat.
– Murilo de Jesus
@Sidon, I edited with the user’s definition. I’m not able to access the chat at the moment
– Murilo de Jesus
Okay, it’s a little confusing, but I posted an answer.
– Sidon