Python: "TypeError: __str__ returned non-string" but still prints to output?

Viewed 153634

I have this piece of code which creates a new note..WHen I try to print I get the following error even though it prints the output

Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Memo=This is my first memo, Tag=example
Traceback (most recent call last):
  File "notebook.py", line 14, in <module>
    print(firstnote)
TypeError: __str__ returned non-string (type NoneType)

note.py

import datetime
class Note:
    def __init__(self, memo, tags):
        self.memo = memo
        self.tags = tags
        self.creation_date = datetime.date.today()

    def __str__(self):
        print('Memo={0}, Tag={1}').format(self.memo, self.tags)


if __name__ == "__main__":
    firstnote = Note('This is my first memo','example')
    print(firstnote)
8 Answers

The problem that you are facing is : TypeError : str returned non-string (type NoneType)

Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error

You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it

 class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

    def __str__(self):
        return self.summary

but if the value you are returning in not of string type then you can do like this to return string value from your str function

*typeconverting the value to string that your str function returns

class Summary(models.Model):
   book = models.ForeignKey(Book,on_delete = models.CASCADE)
   summary = models.TextField(max_length=600)

   def __str__(self):
       return str(self.summary)
            `

In the Model's __str__ method, you are returning a value which is null.

For example:

class X(models.Model):
    name = models.CharField(_('Name'), null=True, blank=True, 
    max_length=150)
    date_of_birth = models.DateField(_('Date of birth'), null=True, blank=True)
    street = models.CharField(_('Street'), max_length=150, blank=True)
    
    def __str__(self):
        return self.name # here the value of name field might be null, so the 

error is showing.

Correct __str__ method will be:

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

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

I Had the same problem, in my case, was because i was returned a digit:

def __str__(self):
    return self.code

str is waiting for a str, not another.

now work good with:

def __str__(self):
    return self.name

where name is a STRING.

I,m newbie at Django. But I share my experience because solved the same case.

My case is that, Someday(no memory) changed(added) some field(memo)'s attribute to null=True. but I totally forgot that my model.py as following.

def __str__(self):
    if self is not None:
        return self.author.memo

So I edited the return value to some other field. That's all.

You probably have some null value in your table. Enter to mysql and delete null value in table.

Related