Search code examples
pythondjangodjango-allauth

Information not storing on tabel Expanding User table Django/Allauth


I have a table with a OneToOneField connection to settings.AUTH_USER_MODEL and when registering the information that should be stored on this second table isnt

Here is my code

On Models

class Cliente(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True)

DEPARTAMENTOS = (
    ("ARTIGAS","ARTIGAS"),
    ("CERRO LARGO","CERRO LARGO"),
    ("DURAZNO", "DURAZNO"),
    ("FLORIDA","FLORIDA"),
    ("MALDONADO","MALDONADO"),
    ("PAYSANDU","PAYSANDU"),
    ("RIVERA","RIVERA"),
    ("SALTO","SALTO"),
    ("SORIANO","SORIANO"),
    ("TREINTA Y TRES", "TREINTA Y TRES"),
    ("CANELONES", "CANELONES"),
    ("COLONIA", "COLONIA"),
    ("FLORES", "FLORES"),
    ("LAVALLEJA", "LAVALLEJA"),
    ("MONTEVIDEO", "MONTEVIDEO"),
    ("RIO NEGRO", "RIO NEGRO"),
    ("ROCHA", "ROCHA"),
    ("SAN JOSE", "SAN JOSE"),
    ("TACUAREMBO", "TACUAREMBO"),
)

SEXO = (
    ("M","MASCULINO"),
    ("F","FEMENINO"),
)

ubicacion_departamento = models.CharField(_('Departamendo de residencia'),max_length=50,choices=DEPARTAMENTOS, blank=False, default="MONTEVIDEO")
#Extendemos desde la clase de usuario base que nos da django para pedir los parametros especificos para nuestros usuarios
fecha_nacimiento = models.DateField(_('Fecha de nacimiento - Formato DÍA/MES/AÑO'), default=django.utils.timezone.now, blank=False)
#A cambiar por lista de posibles ubicaciones
sexo = models.CharField(_('Sexo'), choices=SEXO, max_length=1, default="M")
#Manejo de foto de perfil
#foto_perfil = models.ImageField(upload_to='fotosPerfil')



name = models.CharField(_('Name of User'), blank=True, max_length=255)

def __str__(self):
    return self.username

def get_absolute_url(self):
    return reverse('users:detail', kwargs={'username': self.username})


REQUIRED_FIELDS = ['ubicacion_departamento','fecha_nacimiento','sexo']

On adapters.py

class RegistroUsuariosAdapter(DefaultAccountAdapter):
    def save_user(self, request, user, form, commit=True):
        data = form.cleaned_data
        user.first_name = data['nombre']
        user.last_name = data['apellido']
        #campos adicionales para los usuarios clieente
        user.ubicacion_departamento = data['ubicacion_departamento']
        user.fecha_nacimiento = data['fecha_nacimiento']
        #Lo que allauth normalmente ya guarda
        user.username = data['username']
        user.email = data['email']
        if 'password1' in data:
            user.set_password(data['password1'])
        else:
            user.set_unusable_password()
        self.populate_username(request,user)
        if commit:
            user.save()
        return user

and on forms.py class FormularioCliente(SignupForm,ModelForm):

#input necesario para usuario pero no relacionado a allauth
nombre = forms.CharField(label='Nombre', strip=True, max_length=50)
apellido = forms.CharField(label='Apellido', strip=True, max_length=50)


class Meta:
    model = Cliente
    fields = "__all__"
    exclude = ['user','name',]

#ubicacion_departamento, fecha_nacimiento, sexo, foto_perfil
def signup(self, request, user):
    user = super(FormularioCliente, self).save(request)

def __init__(self, *args, **kwargs):
    super(FormularioCliente, self).__init__(*args, **kwargs)

Solution

  • Problem was that second table was for Proveedor, which inherits from User.

    Solution was creating a functino that would save the proveedor but firsthand save it as a user to be able to reference it in the one to one field (solving foreign key constraint problems).