Django __str__ returned non-string (type NoneType)

Viewed 23193

I am getting __str__ returned non-string (type NoneType) error at edit Product Model object

enter image description here

Product Model

class Product(models.Model):
    ProductName = models.CharField(blank=True, max_length=250)
    Price = models.FloatField(blank=True, default=9.99)
    Tax = models.FloatField(blank=True, null=True, default=0.0)
    StoreId = models.IntegerField(blank=True, null=True)
    RelatedStore = models.ForeignKey(Store, blank=True, null=True)
    Category = models.CharField(max_length=200,
                                blank=True, null=True,
                                default='No Specific Category')
    ProductImage = models.CharField(max_length=400, null=True, blank=True)
    Features = models.TextField(blank=True, null=True)
    ProductSize = models.IntegerField(blank=True, null=True, default=3)
    FavoriteField = models.BooleanField(blank=True, default=False)
    Active = models.BooleanField(blank=True, default=True)

    def __unicode__(self):
        return self.ProductName

    def __str__(self):
        return self.ProductName

Any helpful answer will be appreciated.

5 Answers

you can try:

def __str__(self):
    return str(self.ProductName) if self.ProductName else ''

I little late but change the return as follows:

def __str__(self):
    return str(self.ProductName)

__str__ returned non-string (type NoneType)

is returned when the model you are accessing OR other models related to it is / are returning an int value on the def __str__ function. Should you be returning an int, be sure to parse the value to a String option.

def __str__(self):
    return str(self.id)

The issue is on Foregienkey :

 RelatedStore = models.ForeignKey(Store, blank=True, null=True)

#edit or delete this:
    def __str__(self):
        return self.ProductName

or else check the Store class there will be some

def_str_(self):
 return self.something 

then it will work fine , I know i am late but that worked for me !!

I found the solution, just make sure that the table (or the model) does not return and does not contain any attribute (or foreign key) whose the table / model returns an integer. You can use this for those attribute if you want to return primary key:

def __str__(self):
        return (str(self.pk))

In your case, make sure that the RelatedStore class / model / table returns a string.

Related