Error when registering user in Django

Asked

Viewed 256 times

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

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • The message says that you are trying to include a "repeated" record, in a table whose field matriculaUsuario has the restriction UNIQUE, 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, 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.

  • You need to check before calling the save(), I suggest testing the Django shell to make sure it is sending the data correctly.

  • @Sidon, the POST output was: first_name 'Test last_name 'Test username 'test matriculaUsuario '222222222222' email '[email protected]' password1 'RSRSRSRS'&#Xa password2 'RSRSRSRS'

  • Log in to the Django admin and try to register some users there to see what happens.

  • @Sidon, the same mistake happens

  • @Sidon, I edited with the user’s definition. I’m not able to access the chat at the moment

  • Okay, it’s a little confusing, but I posted an answer.

Show 4 more comments

1 answer

0

I understand you need to just extend the User adding some fields, without necessarily changing anything in the auth, I mean, you’re not customizing the authentication, right? but I couldn’t understand what you wanted to do in the model Usuario, in my view should be simpler, either you really customize everything or just extend the class User embedded in Django, I’m going to give a example of the documentation itself (making a small adaptation to your context, but calling your student) by placing the extended class in admin, which you did not do:

py.models

from django.db import models
from django.contrib.auth.models import User

class Aluno(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Adicionando os campos (adicione qtos precisar)
    matricula = models.CharField('Matrícula', max_length=12)

admin py.

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Aluno

class AlunoInline(admin.StackedInline):
    model = Aluno
    can_delete = False
    verbose_name = 'Informações Pessoais'

class UserAdmin(BaseUserAdmin):
    inlines = (AlunoInline,)

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

@admin.register(Aluno)
class AlunoAdmin(admin.ModelAdmin):
    model = Aluno
    list_display = ('user', 'matricula',)

Okay, now go to the Django admin and you’ll have:

Admin djangoi

You can add students (user) either by auth (AUTHENTICATION AND AUTHORIZATION) or by USERS (Students)

Although repl.it still has some limitations with Django, left working there, to run you need to make a Fork, Migrations and create the superuser (just follow the instructions of the CLI panel on the lower right side).

inserir a descrição da imagem aqui

  • I am facing the following problem: UNIQUE Constraint failed: polls_student.user_id. What can it be? I already set a default value, but I did not succeed.

  • Since Django works with a lot of abstraction it is difficult to understand what you want, I suggest you break the problem in smaller pieces, based on my answer, try to put the User in admin, you are working directly with User. Another thing, look in the database (to open the database, if you have nothing, try the dbeaver community) See what you have already registered there and see if there is ujma clue of the reason for this message. Tb n entendi pq vc the methods create_user_usuario and save_user_usuario. Could explain?

  • I tried to create a new bank from scratch, and the problem continues. Apparently, my problem is in the Unique field. I copied your code and when I went to make the makemigratios, the id , which would be the primary student, gave error for being Unique=True. I can put the user in Admin, the problem is in the registration of a new user only. When I will edit your registration later, no error occurs.

  • About the methods create_user_usuario and save_user_usuario, were research tests performed on the internet only

  • I created a new project and the problem no longer occurs. It will be boring to have to populate it again, but the important thing is to work. Thanks for the help.

  • I suggest that you focus first on something simple, use the structure of my answer, remove those 2 methods that you put but do not know how to explain. If I had to point out a negative thing in Jango, it would be the level of abstraction, and because of that, you can walk into a tremendous trap if you go jamming code into your system without deeply understanding why. The price to pay for it in the future is very high.

  • Thanks for the tips. I’m new in Django and I’m starting to do my final project in college, I’m still a little lost, but now I’ll focus on the structure to later popular the bank

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.