I faced this error: __str__ returned non-string (type User)
in admin tool when clicking on a project to display the details. This error can also happen in terminal when doing:
# terminal
>>> Contributor.objects.all().first()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/doro/.local/share/virtualenvs/SoftDesk_project-rOWNEwjK/lib/python3.10/site-packages/django/db/models/base.py", line 588, in __repr__
return "<%s: %s>" % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type User)
The solution I came up with:
# models.py
class Contributor(models.Model):
user = models.ForeignKey(
"api.User",
on_delete=models.CASCADE,
related_name="users",
verbose_name=_("user"),
)
def __str__(self):
return self.user.username
class Project(models.Model):
name = models.CharField(max_length=100, verbose_name=_("name of project"))
author = models.ForeignKey(
"api.Contributor",
on_delete=models.CASCADE,
blank=True,
related_name="project_author",
verbose_name=_("project author"),
)
def __str__(self):
return f"{self.name} <{self.author.user}>"
The error was pointing to the __str__
method of the Contributor model. When I added .username
the error was gone. With self.user
I was just pointing to the user model but not to the attribute which should be displayed.
It has to be a string like the username, first_name, last_name etc.