Luke
Luke

Reputation: 155

Django: returning __str__ error when I try to add new instance of model from admin dashboard

When I try to add a new instance of any model that has Campus as a foreign key, I get this error, and I'm dumbfounded.

error message

Here is the code for the Campus model

from django.db import models

class Campus(models.Model):
name = models.TextField(max_length = 100, default=None)
description = models.TextField(max_length = 100, default=None)

def __str__(self):
    return self.name

I'm not sure what the problem is with the str function as this is what I do for all of my basic models.

Thanks for any help you can give

Upvotes: 0

Views: 34

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

It is not the __str__ of the Campus that is the problem here. It is some other model (or something else) that has as __str__ something that returns a Campus object (likely with a ForeignKey/OneToOneField), and thus does not call __str__ on that object.

So that normally happens if you have a model that looks like:

class MyOtherModel(models.Model):
    campus = models.ForeignKey(Campus, on_delete=models.CASCADE)

    # …

    def __str__(self):
        return self.campus

Here the __str__ method thus returns a Campus object, not a string. You can fix it by convertin the Campus object to a string, for example by calling str(..) on it:

class MyOtherModel(models.Model):
    campus = models.ForeignKey(Campus, on_delete=models.CASCADE)

    # …

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

Upvotes: 1

Related Questions