简体   繁体   中英

How to fix Attribute error even though it is imported

While I was adding my dislike button I have encountered another problem An attribute error. I hope someone can help me fix it. It says Post object has no attribute even though it does.

Traceback:

AttributeError at /article/27
'Post' object has no attribute 'total_dislikes'
Request Method: GET
Request URL:    http://127.0.0.1:8000/article/27
Django Version: 3.2.3
Exception Type: AttributeError
Exception Value:    
'Post' object has no attribute 'total_dislikes'
Exception Location: C:\simpleblog\ablog\myblog\views.py, line 67, in get_context_data
Python Executable:  C:\Users\Selvi\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.1
Python Path:    
['C:\\simpleblog\\ablog',
 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']

views.py(where the traceback occured)

from .models import Post, Category

def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    liked = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True
    
    return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))

def DislikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    disliked = False
    if post.dislikes.filter(id=request.user.id).exists():
        post.dislikes.remove(request.user)
        disliked = False
    else:
        post.dislikes.add(request.user)
        disliked = True
    
    return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))

class ArticleDetailView(DetailView):
    model = Post
    template_name = 'article_details.html'

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
        
        thing = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = thing.total_likes()
        total_dislikes = thing.total_dislikes() 
        
        disliked = False
        if thing.dislikes.filter(id=self.request.user.id).exists():
            disliked = True

        liked = False
        if thing.likes.filter(id=self.request.user.id).exists():
            liked = True

        context["cat_menu"] = cat_menu
        context["total_likes"] = total_likes
        context["liked"] = liked
        
        context["total_dislikes"] = total_dislikes
        context["disliked"] = disliked
        return context

models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    title_tag = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default='intro')
    likes = models.ManyToManyField(User, related_name='post_likes')
    dislikes = models.ManyToManyField(User, related_name='post_dislikes')

If any other python file or html file is needed please feel free to ask.

Reason for Attribute error ​is Your Post model does not have a total_likes nor a total_ dislikes method.

You can write methods for the same in your models.py

def total_likes(self)
   return self.likes.all().count()
def total_dislikes(self)
   return self.dislikes.all().count()

in your Post class and now you can simply use thing.total_likes and thing.total_dislikes .

Like Hussain said, Your Post model has no total_likes or total_dislikes method. You can do this instead:

total_likes = thing.post_likes.all().count()


total_dislikes = thing.post_dislikes.all().count()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM