Can not assign "'1'": "Customer.type_client" must be to "Customer_type" instance

0

I am trying to save the form I made in django which has a foreignkey from the client model to the client type model but at the time of saving this error comes out.

  

Can not assign "'1'": "Customer.type_client" must be to "Customer_type"   instance

modelos.py

class TipoCliente(models.Model):
    codigo = models.IntegerField()
    descripcion = models.CharField(max_length=40)

class Cliente(models.Model):
    tipo_cliente = models.ForeignKey('TipoCliente')
    nombre = models.CharField(max_length=80)

views.py

tipo_cliente = TipoCliente.objects.all()

cliente = Cliente()
cliente.tipo_cliente = request.POST['tipo_cliente']
cliente.nombre = request.POST['nombre']
cliente.save()

error

  

ValueError at / general / clients

     

Can not assign "'1'": "Client.type_client" must be to "TypeClient" instance.

     

Django Version: 1.10.2

     

Exception Type: ValueError

     

Exception Value:

     

Can not assign "'1'": "Client.type_client" must be to "TypeClient" instance.

Using the Django form works perfectly but I have to do it without using the Django form.

    
asked by jhon1946 30.10.2016 в 19:39
source

2 answers

1

The error is clear, tipo_cliente must receive an object of type TipoCliente but instead you assign a string that you receive by POST Filter the TipoCliente by the type you receive by POST to then assign the attribute tipo_cliente of the Model Cliente

cliente = Cliente()
cliente.tipo_cliente = TipoCliente.objects.get(codigo = request.POST['tipo_cliente'])
cliente.nombre = request.POST['nombre']
cliente.save()
    
answered by 30.10.2016 / 19:56
source
1

I think that's how it will work for you:

tipo = TipoCliente.objects.get(pk = request.POST['tipo_cliente']) # Obtengo el objeto de TipoCliente
cliente = Cliente()
cliente.tipo_cliente = tipo
cliente.nombre = request.POST['nombre']
cliente.save()

What is happening is that you are assigning an integer to a field that is a foreign key, as in Django a mapping of the database is made that foreign one becomes an object of type TypeClient. That's when the incompatibility arises

    
answered by 30.10.2016 в 19:46