Python - Why does __str__ want something returned when it called? I have print functions inside of __str__
Date : March 29 2020, 07:55 AM
hop of those help? As per the __str__ docs, def __str__(self):
return "Vehicle Type: {}\nMake: {}\nModel: {}\nYear: {}\nMiles: {}" \
.format(self.typ, self.make, self.model, self.year, self.miles)
|
Django __str__ returned non-string (type tuple), i didn't define __str__
Date : March 29 2020, 07:55 AM
hop of those help? Look for a stray comma at the end of any __str__ definitions that you did write. Returning a value with a comma at the end will turn your value into a tuple containing that value.
|
Cannot make custom __str__ calling parent's __str__ in Django
Date : March 29 2020, 07:55 AM
seems to work fine Ok, I managed to know what was happening. It was because of the decorator python_2_unicode_compatible (from django.utils.encoding import python_2_unicode_compatible). Here's the traceback where problem starts: /my/path/to/django/utils/six in <lambda>(self)
840 klass.__name__)
841 klass.__unicode__ = klass.__str__
--> 842 klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
843 return klass
844
def str(self):
return "foo"
def __str__(self):
return self.str()
|
how to activate __str__ dunder method using instance and fix error:"__str__ returned non-string (type NoneType)&quo
Date : March 29 2020, 07:55 AM
hop of those help? As the error says, you need to return the new string representation of the class instance you created in the overriden __str__ dunder method. def __str__(self):
self.great_dev=math.gcd(self.p,self.q)
self.p=self.p/self.great_dev
self.q=self.q/self.great_dev
# return the updated string representation
return "{self.p}/{self.q}".format(self=self)
|
how to use __str__ with foreign key '__str__ returned non-string (type Product)'
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can not return something other than a string from the __str__ method. self.product is not a string, but a Product object. You can however call str(..) over it, to get the textual representation of that Product: class ProductOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True)
def __str__(self):
return str(self.product)
|