How to Solve Error Message __str__ returned non-string (type NoneType) when running Django Application

Posted on

Introduction

This is an article where the main content is about to describe how to solve an error message. The error appear in the administration page of a Django-based application. It is when a part of the script of a Django-based application. Actually, that part of the script is a model exist in the ‘models.py’ file. Furthermore, there is a specific line of source code for registering a certain model to the administration module. But registering it to the administration module trigger the error to appear. The following is the model which exist in the ‘models.py’ file :

class Topic(models.Model):
    name = models.CharField(max_length=200)
    def __str__(self):
        return self

Furthermore, the following line defines the registration of the above model to the administration module :

from django.contrib import admin
from .models import Room, Topic, Message
# Register your models here.
admin.site.register(Topic)

The execution of the Django-based application is generating the following error message as part of the output of the internal running Django server :

...
 result_repr = display_for_value(value, empty_value_display, boolean)
File "C:\python-3.10\lib\site-packages\django\contrib\admin\utils.py", line 429, in display_for_value
return str(value)
TypeError: __str__ returned non-string (type Topic)
[30/Jan/2022 19:27:55] "GET /admin/base/topic/ HTTP/1.1" 500 288412

Solution

According to the error message, it cannot return the value of the non-string type of Topic. In this case, ‘Topic’ is a model. Actually, administration page displaying list of the model need to print the string version of the model. In this context, the model is ‘Topic’ and it need the string representation so that it can be printed in the page. Since the function of __str__ in that model does not return the string version, it get an error message. It return ‘self’ which is pointing out to the model itself. So, it will generate an error since it is not a string representation. In order to do that, just revise the __str__ method or function to return a string representation. Just pick any field, attribute or property which has a string type as the return value. In this context, for an example, it is the attribute or property with the namae of ‘name’. So, the revision of the __str__ function or method is as follows :

class Topic(models.Model):
    name = models.CharField(max_length=200)
    def __str__(self):
        return self.name

Run the internal Django server once more and also access the administration module page. If there are no more errors exist, the administration module page will perfectly display and list the ‘Topic’ module with the name as its string representation.

Leave a Reply