UNIQUE constraint failed: “app”_customuser.username











up vote
0
down vote

favorite












I´m new in Django. I registered a superuser with "createsuperuser" and now I want to create a normal user with my custom registration form but this send me this error about unique constraint:



IntegrityError at /registro/registrar/



UNIQUE constraint failed: registroUsuario_customuser.username



Request Method: POST
Request URL: http://127.0.0.1:8000/registro/registrar/
Django Version: 2.0.9
Exception Type: IntegrityError
Exception Value:



UNIQUE constraint failed: registroUsuario_customuser.username



Exception Location: C:UsersririaDesktopperrosUnidad3myvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 303
Python Executable: C:UsersririaDesktopperrosUnidad3myvenvScriptspython.exe
Python Version: 3.7.0
Python Path:



['C:UsersririaDesktopperrosUnidad3',
'C:UsersririaDesktopperrosUnidad3myvenvScriptspython37.zip',
'C:UsersririaAppDataLocalProgramsPythonPython37DLLs',
'C:UsersririaAppDataLocalProgramsPythonPython37lib',
'C:UsersririaAppDataLocalProgramsPythonPython37',
'C:UsersririaDesktopperrosUnidad3myvenv',
'C:UsersririaDesktopperrosUnidad3myvenvlibsite-packages']



Server time: Lun, 19 Nov 2018 17:56:33 -0300



This is my code:



models.py



class CustomUserManager(UserManager):

def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None):
if not run:
raise ValueError("Usuario debe ingresar su run")

user = self.model(
run = run,
email = self.normalize_email(email),
fechaNac = fechaNac,
nombre = nombre,
apellido = apellido,
telefono = telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password):

user = self.create_user(
run = run,
password=password,
email=email,
fechaNac=fechaNac,
nombre=nombre,
apellido=apellido,
telefono=telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.is_admin = True
user.save(using=self._db)
return user



class CustomUser(AbstractUser):
run = models.CharField(max_length=9, unique=True, primary_key=True)
email = models.EmailField(max_length=30, unique=True, verbose_name='Direccion de correo') #obtener email con get_email_field_name()
fechaNac = models.DateField(verbose_name="Fecha de Nacimiento")
nombre = models.CharField(max_length=15, unique=False) #get_full_name()???
apellido = models.CharField(max_length=15)
telefono = models.CharField(max_length=9)
regiones = models.CharField(max_length=40)
comunas = models.CharField(max_length=40)
tipo_viviendas = ((1,'Casa con patio grande'),(2,'Casa con patio pequeño'),(3,'Casa sin patio'),(4,'Departamento'))
tipo_vivienda = models.IntegerField(choices=tipo_viviendas)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)

USERNAME_FIELD = 'run'
REQUIRED_FIELDS = ['email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda']
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'run'

objects = CustomUserManager()



def __str__(self):
return self.run

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, misPerris):
return True

@property
def is_staff(self):
return self.is_admin


forms.py



class UserCreationForm(forms.ModelForm):
#crear new users incluyendo todos los campos requeridos
password1 = forms.CharField(label='contrasena', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contrasena', widget=forms.PasswordInput)

class Meta:
model = CustomUser
fields = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda')

def clean_password2(self):
#para ver que las 2 passwords sean iguales
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Las Contrasenas no son iguales")
return password2

def save(self, commit=True):
#guardar la contrasena en hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
#este es para actualizar al usuario y todos sus campos excepto la password creo
password = ReadOnlyPasswordHashField

class Meta:
model = CustomUser
fields = ('run','password','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_active','is_admin')

def clean_password(self):
#
return self.initial["password"]

class UserAdmin(BaseUserAdmin):
#el form para agregar y cambia instancias de usuario
form = UserChangeForm
add_form = UserCreationForm

#campos que apareceran en admin en el User Model
list_display = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('run','password')}),
('Personal info', {'fields': ('email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','password1','password2')}
),
)
search_fields = ('run',)
ordering = ('run',)
filter_horizontal = ()


views.py



def registrar(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(login_redirect)
else:
form = UserCreationForm()

args = {'form': form}
return render(request, 'registro/registro.html', args)









share|improve this question






















  • On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
    – Walucas
    Nov 19 at 21:13












  • Didn´t work :( I think probably the database have another username field maybe
    – Ernesto Andres Cabello Venegas
    Nov 19 at 23:35










  • Its not to work. I want to see the print output.
    – Walucas
    Nov 19 at 23:36















up vote
0
down vote

favorite












I´m new in Django. I registered a superuser with "createsuperuser" and now I want to create a normal user with my custom registration form but this send me this error about unique constraint:



IntegrityError at /registro/registrar/



UNIQUE constraint failed: registroUsuario_customuser.username



Request Method: POST
Request URL: http://127.0.0.1:8000/registro/registrar/
Django Version: 2.0.9
Exception Type: IntegrityError
Exception Value:



UNIQUE constraint failed: registroUsuario_customuser.username



Exception Location: C:UsersririaDesktopperrosUnidad3myvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 303
Python Executable: C:UsersririaDesktopperrosUnidad3myvenvScriptspython.exe
Python Version: 3.7.0
Python Path:



['C:UsersririaDesktopperrosUnidad3',
'C:UsersririaDesktopperrosUnidad3myvenvScriptspython37.zip',
'C:UsersririaAppDataLocalProgramsPythonPython37DLLs',
'C:UsersririaAppDataLocalProgramsPythonPython37lib',
'C:UsersririaAppDataLocalProgramsPythonPython37',
'C:UsersririaDesktopperrosUnidad3myvenv',
'C:UsersririaDesktopperrosUnidad3myvenvlibsite-packages']



Server time: Lun, 19 Nov 2018 17:56:33 -0300



This is my code:



models.py



class CustomUserManager(UserManager):

def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None):
if not run:
raise ValueError("Usuario debe ingresar su run")

user = self.model(
run = run,
email = self.normalize_email(email),
fechaNac = fechaNac,
nombre = nombre,
apellido = apellido,
telefono = telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password):

user = self.create_user(
run = run,
password=password,
email=email,
fechaNac=fechaNac,
nombre=nombre,
apellido=apellido,
telefono=telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.is_admin = True
user.save(using=self._db)
return user



class CustomUser(AbstractUser):
run = models.CharField(max_length=9, unique=True, primary_key=True)
email = models.EmailField(max_length=30, unique=True, verbose_name='Direccion de correo') #obtener email con get_email_field_name()
fechaNac = models.DateField(verbose_name="Fecha de Nacimiento")
nombre = models.CharField(max_length=15, unique=False) #get_full_name()???
apellido = models.CharField(max_length=15)
telefono = models.CharField(max_length=9)
regiones = models.CharField(max_length=40)
comunas = models.CharField(max_length=40)
tipo_viviendas = ((1,'Casa con patio grande'),(2,'Casa con patio pequeño'),(3,'Casa sin patio'),(4,'Departamento'))
tipo_vivienda = models.IntegerField(choices=tipo_viviendas)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)

USERNAME_FIELD = 'run'
REQUIRED_FIELDS = ['email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda']
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'run'

objects = CustomUserManager()



def __str__(self):
return self.run

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, misPerris):
return True

@property
def is_staff(self):
return self.is_admin


forms.py



class UserCreationForm(forms.ModelForm):
#crear new users incluyendo todos los campos requeridos
password1 = forms.CharField(label='contrasena', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contrasena', widget=forms.PasswordInput)

class Meta:
model = CustomUser
fields = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda')

def clean_password2(self):
#para ver que las 2 passwords sean iguales
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Las Contrasenas no son iguales")
return password2

def save(self, commit=True):
#guardar la contrasena en hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
#este es para actualizar al usuario y todos sus campos excepto la password creo
password = ReadOnlyPasswordHashField

class Meta:
model = CustomUser
fields = ('run','password','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_active','is_admin')

def clean_password(self):
#
return self.initial["password"]

class UserAdmin(BaseUserAdmin):
#el form para agregar y cambia instancias de usuario
form = UserChangeForm
add_form = UserCreationForm

#campos que apareceran en admin en el User Model
list_display = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('run','password')}),
('Personal info', {'fields': ('email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','password1','password2')}
),
)
search_fields = ('run',)
ordering = ('run',)
filter_horizontal = ()


views.py



def registrar(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(login_redirect)
else:
form = UserCreationForm()

args = {'form': form}
return render(request, 'registro/registro.html', args)









share|improve this question






















  • On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
    – Walucas
    Nov 19 at 21:13












  • Didn´t work :( I think probably the database have another username field maybe
    – Ernesto Andres Cabello Venegas
    Nov 19 at 23:35










  • Its not to work. I want to see the print output.
    – Walucas
    Nov 19 at 23:36













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I´m new in Django. I registered a superuser with "createsuperuser" and now I want to create a normal user with my custom registration form but this send me this error about unique constraint:



IntegrityError at /registro/registrar/



UNIQUE constraint failed: registroUsuario_customuser.username



Request Method: POST
Request URL: http://127.0.0.1:8000/registro/registrar/
Django Version: 2.0.9
Exception Type: IntegrityError
Exception Value:



UNIQUE constraint failed: registroUsuario_customuser.username



Exception Location: C:UsersririaDesktopperrosUnidad3myvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 303
Python Executable: C:UsersririaDesktopperrosUnidad3myvenvScriptspython.exe
Python Version: 3.7.0
Python Path:



['C:UsersririaDesktopperrosUnidad3',
'C:UsersririaDesktopperrosUnidad3myvenvScriptspython37.zip',
'C:UsersririaAppDataLocalProgramsPythonPython37DLLs',
'C:UsersririaAppDataLocalProgramsPythonPython37lib',
'C:UsersririaAppDataLocalProgramsPythonPython37',
'C:UsersririaDesktopperrosUnidad3myvenv',
'C:UsersririaDesktopperrosUnidad3myvenvlibsite-packages']



Server time: Lun, 19 Nov 2018 17:56:33 -0300



This is my code:



models.py



class CustomUserManager(UserManager):

def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None):
if not run:
raise ValueError("Usuario debe ingresar su run")

user = self.model(
run = run,
email = self.normalize_email(email),
fechaNac = fechaNac,
nombre = nombre,
apellido = apellido,
telefono = telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password):

user = self.create_user(
run = run,
password=password,
email=email,
fechaNac=fechaNac,
nombre=nombre,
apellido=apellido,
telefono=telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.is_admin = True
user.save(using=self._db)
return user



class CustomUser(AbstractUser):
run = models.CharField(max_length=9, unique=True, primary_key=True)
email = models.EmailField(max_length=30, unique=True, verbose_name='Direccion de correo') #obtener email con get_email_field_name()
fechaNac = models.DateField(verbose_name="Fecha de Nacimiento")
nombre = models.CharField(max_length=15, unique=False) #get_full_name()???
apellido = models.CharField(max_length=15)
telefono = models.CharField(max_length=9)
regiones = models.CharField(max_length=40)
comunas = models.CharField(max_length=40)
tipo_viviendas = ((1,'Casa con patio grande'),(2,'Casa con patio pequeño'),(3,'Casa sin patio'),(4,'Departamento'))
tipo_vivienda = models.IntegerField(choices=tipo_viviendas)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)

USERNAME_FIELD = 'run'
REQUIRED_FIELDS = ['email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda']
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'run'

objects = CustomUserManager()



def __str__(self):
return self.run

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, misPerris):
return True

@property
def is_staff(self):
return self.is_admin


forms.py



class UserCreationForm(forms.ModelForm):
#crear new users incluyendo todos los campos requeridos
password1 = forms.CharField(label='contrasena', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contrasena', widget=forms.PasswordInput)

class Meta:
model = CustomUser
fields = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda')

def clean_password2(self):
#para ver que las 2 passwords sean iguales
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Las Contrasenas no son iguales")
return password2

def save(self, commit=True):
#guardar la contrasena en hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
#este es para actualizar al usuario y todos sus campos excepto la password creo
password = ReadOnlyPasswordHashField

class Meta:
model = CustomUser
fields = ('run','password','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_active','is_admin')

def clean_password(self):
#
return self.initial["password"]

class UserAdmin(BaseUserAdmin):
#el form para agregar y cambia instancias de usuario
form = UserChangeForm
add_form = UserCreationForm

#campos que apareceran en admin en el User Model
list_display = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('run','password')}),
('Personal info', {'fields': ('email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','password1','password2')}
),
)
search_fields = ('run',)
ordering = ('run',)
filter_horizontal = ()


views.py



def registrar(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(login_redirect)
else:
form = UserCreationForm()

args = {'form': form}
return render(request, 'registro/registro.html', args)









share|improve this question













I´m new in Django. I registered a superuser with "createsuperuser" and now I want to create a normal user with my custom registration form but this send me this error about unique constraint:



IntegrityError at /registro/registrar/



UNIQUE constraint failed: registroUsuario_customuser.username



Request Method: POST
Request URL: http://127.0.0.1:8000/registro/registrar/
Django Version: 2.0.9
Exception Type: IntegrityError
Exception Value:



UNIQUE constraint failed: registroUsuario_customuser.username



Exception Location: C:UsersririaDesktopperrosUnidad3myvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 303
Python Executable: C:UsersririaDesktopperrosUnidad3myvenvScriptspython.exe
Python Version: 3.7.0
Python Path:



['C:UsersririaDesktopperrosUnidad3',
'C:UsersririaDesktopperrosUnidad3myvenvScriptspython37.zip',
'C:UsersririaAppDataLocalProgramsPythonPython37DLLs',
'C:UsersririaAppDataLocalProgramsPythonPython37lib',
'C:UsersririaAppDataLocalProgramsPythonPython37',
'C:UsersririaDesktopperrosUnidad3myvenv',
'C:UsersririaDesktopperrosUnidad3myvenvlibsite-packages']



Server time: Lun, 19 Nov 2018 17:56:33 -0300



This is my code:



models.py



class CustomUserManager(UserManager):

def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None):
if not run:
raise ValueError("Usuario debe ingresar su run")

user = self.model(
run = run,
email = self.normalize_email(email),
fechaNac = fechaNac,
nombre = nombre,
apellido = apellido,
telefono = telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password):

user = self.create_user(
run = run,
password=password,
email=email,
fechaNac=fechaNac,
nombre=nombre,
apellido=apellido,
telefono=telefono,
regiones = regiones,
comunas = comunas,
tipo_vivienda = tipo_vivienda,
)

user.is_admin = True
user.save(using=self._db)
return user



class CustomUser(AbstractUser):
run = models.CharField(max_length=9, unique=True, primary_key=True)
email = models.EmailField(max_length=30, unique=True, verbose_name='Direccion de correo') #obtener email con get_email_field_name()
fechaNac = models.DateField(verbose_name="Fecha de Nacimiento")
nombre = models.CharField(max_length=15, unique=False) #get_full_name()???
apellido = models.CharField(max_length=15)
telefono = models.CharField(max_length=9)
regiones = models.CharField(max_length=40)
comunas = models.CharField(max_length=40)
tipo_viviendas = ((1,'Casa con patio grande'),(2,'Casa con patio pequeño'),(3,'Casa sin patio'),(4,'Departamento'))
tipo_vivienda = models.IntegerField(choices=tipo_viviendas)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)

USERNAME_FIELD = 'run'
REQUIRED_FIELDS = ['email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda']
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'run'

objects = CustomUserManager()



def __str__(self):
return self.run

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, misPerris):
return True

@property
def is_staff(self):
return self.is_admin


forms.py



class UserCreationForm(forms.ModelForm):
#crear new users incluyendo todos los campos requeridos
password1 = forms.CharField(label='contrasena', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contrasena', widget=forms.PasswordInput)

class Meta:
model = CustomUser
fields = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda')

def clean_password2(self):
#para ver que las 2 passwords sean iguales
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Las Contrasenas no son iguales")
return password2

def save(self, commit=True):
#guardar la contrasena en hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
#este es para actualizar al usuario y todos sus campos excepto la password creo
password = ReadOnlyPasswordHashField

class Meta:
model = CustomUser
fields = ('run','password','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_active','is_admin')

def clean_password(self):
#
return self.initial["password"]

class UserAdmin(BaseUserAdmin):
#el form para agregar y cambia instancias de usuario
form = UserChangeForm
add_form = UserCreationForm

#campos que apareceran en admin en el User Model
list_display = ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('run','password')}),
('Personal info', {'fields': ('email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('run','email','fechaNac','nombre','apellido','telefono','regiones','comunas','tipo_vivienda','password1','password2')}
),
)
search_fields = ('run',)
ordering = ('run',)
filter_horizontal = ()


views.py



def registrar(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect(login_redirect)
else:
form = UserCreationForm()

args = {'form': form}
return render(request, 'registro/registro.html', args)






python django django-models django-forms






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 at 21:09









Ernesto Andres Cabello Venegas

95




95












  • On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
    – Walucas
    Nov 19 at 21:13












  • Didn´t work :( I think probably the database have another username field maybe
    – Ernesto Andres Cabello Venegas
    Nov 19 at 23:35










  • Its not to work. I want to see the print output.
    – Walucas
    Nov 19 at 23:36


















  • On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
    – Walucas
    Nov 19 at 21:13












  • Didn´t work :( I think probably the database have another username field maybe
    – Ernesto Andres Cabello Venegas
    Nov 19 at 23:35










  • Its not to work. I want to see the print output.
    – Walucas
    Nov 19 at 23:36
















On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
– Walucas
Nov 19 at 21:13






On the view, use: save(commit=False) and print the value of run. Probably the initial super user has the same id as the first one you are creating with your form
– Walucas
Nov 19 at 21:13














Didn´t work :( I think probably the database have another username field maybe
– Ernesto Andres Cabello Venegas
Nov 19 at 23:35




Didn´t work :( I think probably the database have another username field maybe
– Ernesto Andres Cabello Venegas
Nov 19 at 23:35












Its not to work. I want to see the print output.
– Walucas
Nov 19 at 23:36




Its not to work. I want to see the print output.
– Walucas
Nov 19 at 23:36

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382664%2funique-constraint-failed-app-customuser-username%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382664%2funique-constraint-failed-app-customuser-username%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'