Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with "__str__ returned non-string (type int)"

I have a problem with a Django Project.

I'll be direct. I am connecting my Django admin to a database that I have on a server, the problem is that when accessing the models in the browser, throws the following error:

TypeError at /admin/crm/asentamiento/78967/
__str__ returned non-string (type int)
Request Method: GET
Request URL:    http://127.0.0.1:8080/admin/crm/asentamiento/78967/
Django Version: 1.8
Exception Type: TypeError
Exception Value:    
__str__ returned non-string (type int)
Exception Location: C:\Spameando\crm_denue2\myvenv\lib\site-packages\django\utils\encoding.py in force_text, line 90
Python Executable:  C:\Spameando\crm_denue2\myvenv\Scripts\python3.exe
Python Version: 3.4.4

And the code for my model is this:

class Asentamiento(models.Model):
    id_asentamiento = models.AutoField(primary_key=True)
    nom_asentamiento = models.CharField(max_length=150)
    tipo_centro = models.CharField(max_length=100)
    nom_centro = models.CharField(max_length=100)
    num_local = models.CharField(max_length=20)
    tipo_asentamiento_id_tipo_asent = models.ForeignKey('TipoAsentamiento', db_column='tipo_asentamiento_id_tipo_asent')
    codigo_postal_id_codpostal = models.ForeignKey('CodigoPostal', db_column='codigo_postal_id_codpostal')
    localidad_id_localidad = models.ForeignKey('Localidad', db_column='localidad_id_localidad')

    class Meta:
        managed = False
        db_table = 'asentamiento'

    def __str__(self):
            return self.nom_asentamiento

I have no idea what the problem is, since I have done the model many times and I always throw the same error, in all other tables and models I have no problem.

The error occurs when I click on some value of my model to see in a window the selected value.

like image 396
Edgar González Avatar asked Nov 15 '16 19:11

Edgar González


1 Answers

Here you're not getting this error because of the return type of Asentamiento model. It return CharField not an Integer type (as mentioned in the error message.)

The error may be due to the return type of TipoAsentamiento, CodigoPostal or the Localidad model. Since these models have One to Many Relationship with the Asentamiento model.

If you're not sure about the return types of these models, then you need to add __str__() method in the model and return a CharField or any other non integer field.

For example, If you want to return a PositiveIntegerField,

def __str__(self):
   return str(self.positive_integer_field_name)
# here, you need to use the str() method to convert the return type into a string. 

If you want to return a Non Integer Field,

def __str__(self):
   return self.non_integer_field_name
like image 188
rangarajan Avatar answered Oct 10 '22 16:10

rangarajan