2

I have a simple model class which I want to return the the value for a field in my Django Admin.

Error Logs from terminal

TypeError: __str__ returned non-string (type NoneType)

models.py

class Solution(models.Model):
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    error = models.ForeignKey(Error, on_delete=models.CASCADE)

    def __str__(self):
        return self.error + " fixed by " + self.user

2 Answers 2

1

I already figured out the solution. Replacing the Solution Model Class to the below code snippet will fix the error.

models.py

class Solution(models.Model):
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    error = models.ForeignKey(Error, on_delete=models.CASCADE)

    def __str__(self):
        return "Solution for " + str(self.error) + " by " + str(self.user)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your solution came just in time
1

It is often better to make use of string formatting [pep-498] or literal string interpolation [pep-498], since this is a more robust tool that will automatically call str(…). Finally it is also more readable:

class Solution(models.Model):
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    error = models.ForeignKey(Error, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.error} fixed by {self.user}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.