简体   繁体   English

如何在 Django Admin 中显示用户所做的活动列表

[英]How to show in Django Admin the list of Activities a user has made

I am trying to get the most out of my Django Blog project and wanted to know how to show in the admin the activities that a user has made like making comments or giving likes to posts.我试图充分利用我的 Django 博客项目,并想知道如何在管理员中显示用户所做的活动,例如发表评论或喜欢帖子。

I need some hints and guidance on how to add this information in the admin.py我需要一些关于如何在 admin.py 中添加此信息的提示和指导

Here is the models.py in Blog App这是博客应用程序中的models.py

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    content = RichTextUploadingField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
    date_posted = models.DateTimeField(default=timezone.now)
    slug = models.SlugField(blank=True, null=True, max_length=120)
    liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')

    def __str__(self):
        return self.title

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

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'Blog Posts'

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField(max_length=300)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.post}-{self.user}-Comment No.{self.pk}"

LIKE_CHOICES = (
    ('Like', 'Like'),
    ('Unlike', 'Unlike')
)


class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, max_length=8)
    created = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.post}-{self.user}-{self.value}"

Here is the models.py in Users App这是用户应用程序中的models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

This is what I have tried in the models.py in Users app but didn't work这是我在用户应用程序中的 models.py 中尝试过的,但没有用

    # Get the no. of posts
    def get_posts_no(self):
        return self.author.all().count()
    # Get the no. of likes
    def get_likes_given(self):
        likes= set.like_set.all()
        total_liked=0
        for item in likes:
            if item.value=='Like':
                total_liked+=1
        return total_liked

"... to add this information in the admin.py" → do you mean to say that you would like to show an additional column in the Django admin site with said information? “...在 admin.py 中添加此信息”→ 您的意思是说您想在 Django 管理站点中显示包含所述信息的附加列吗? If so, then the answer is:如果是这样,那么答案是:

In your admin.py, extend the PostAdmin class with a custom queryset and add comments_count and likes_count to list_display = (...) :在您的 admin.py 中,使用自定义查询集扩展 PostAdmin 类,并将comments_countlikes_count添加到list_display = (...)

from django.contrib import admin
from django.db.models import Count
from .models import Post


class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'date_posted', 'comments_count', 'likes_count')

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(
            _comments_count=Count('comment_set', distinct=True),
            _likes_count=Count('like_set', distinct=True)
        )
        return queryset

    def comments_count(self, obj):
        if hasattr(obj, '_comments_count'):
            return obj._comments_count
        return None

    def likes_count(self, obj):
        if hasattr(obj, '_likes_count'):
            return obj._likes_count
        return None

    comments_count.admin_order_field = '_comments_count'
    likes_count.admin_order_field = '_likes_count'


admin.site.register(Post, PostAdmin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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