Django Blog app (Error): __str__ returned non-string (type User)

2,143 views
Skip to first unread message

robertlls4480

unread,
Oct 11, 2018, 7:20:33 AM10/11/18
to Django users

I'm trying to make a blog website app and i am trying to make a comment feature. But when i try to add a comment with the admin page i get an error.


The Error:


models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title


    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    approved = models.BooleanField(default=False)

    def approved(self):
        self.approved = True
        self.save()

    def __str__(self):
        return self.author


admin.py

from django.contrib import admin
from .models import Post, Comment

admin.site.register(Post)

class CommentAdmin(admin.ModelAdmin):
    list_display = ('author', 'approved')

admin.site.register(Comment, CommentAdmin)

Ігор Магур

unread,
Oct 11, 2018, 7:31:00 AM10/11/18
to Django users
In class Comment in str method you need to user.username or something you want as string, now you are returning full user object. Ex def __str__(self): return user.username

Ігор Магур

unread,
Oct 11, 2018, 7:50:09 AM10/11/18
to Django users
Sorry correct return self.author.username

robertlls4480

unread,
Oct 11, 2018, 7:53:44 AM10/11/18
to Django users
thanks, that helped alot :D
Reply all
Reply to author
Forward
0 new messages