如何在Django中为博客创建类似功能

时间:2019-03-30 18:02:03

标签: python django

我必须为我的国际象棋俱乐部建立一个博客,我想为帖子提供类似的功能。当用户喜欢该帖子时,喜欢的次数就会增加,并且该帖子的显示在用户个人资料中。

这是我到目前为止所做的:

这是我的帖子模型:

class Post(models.Model):
    title = models.CharField(max_length=100)
    overview = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    content = HTMLField()
    is_aproved = models.BooleanField(default=False)
    # comment_count = models.IntegerField(default = 0)
    # view_count = models.IntegerField(default = 0)
    slug = models.SlugField(unique=True, blank=True)
    likes = models.ManyToManyField(
        settings.AUTH_USER_MODEL, blank=True, related_name='post_likes')
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    thumbnail = models.ImageField()
    categories = models.ManyToManyField(Category)
    featured = models.BooleanField()
    previous_post = models.ForeignKey(
        'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True)
    next_post = models.ForeignKey(
        'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True)

    def __str__(self):
        return self.title

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

    def get_update_url(self):
        return reverse('post-update', kwargs={
            'id': self.id
        })

    def get_delete_url(self):
        return reverse('post-delete', kwargs={
            'id': self.id
        })

    @property
    def get_comments(self):
        return self.comments.all().order_by('-timestamp')

    @property
    def comment_count(self):
        return Comment.objects.filter(post=self).count()

    @property
    def view_count(self):
        return PostView.objects.filter(post=self).count()

这是我的观点:

def post(request, id):
    category_count = get_category_count()
    most_recent = Post.objects.order_by('-timestamp')[:3]
    post = get_object_or_404(Post, id=id)

    if request.user.is_authenticated:
        PostView.objects.get_or_create(user=request.user, post=post)

    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            return redirect(reverse("post-detail", kwargs={
                'id': post.pk
            }))
    context = {
        'form': form,
        'post': post,
        'most_recent': most_recent,
        'category_count': category_count,
        'form': form
    }
    return render(request, 'post.html', context)

您能帮助我实现类似功能

1 个答案:

答案 0 :(得分:0)

您需要另一个模型才能在Django中获得喜欢的功能。创建一个像这样的模型-

class PostLikes(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    created = models.DateTimeField(auto_now_add=True)

然后创建一个视图以将该实例添加到PostLikes模型中-

def like_others_post(request, post_id):
    new_like, created = PostLikes.objects.get_or_create(user=request.user, 
                                                   post_id=post_id)
    if not created:
        # you may get and delete the object as the user may already liked this 
        post before

我们正在使用get或create来避免重复点赞。因此,用户可以单击多次,但是,相似实例仅存储一次。

然后在Post模型中添加一种方法来获取点赞次数-

def Post(models.Model):
    ...
    ...
    @property
    def view_count(self):
        return PostLikes.objects.filter(post=self).count()

要在您的帖子视图中查找当前用户是否已经喜欢显示的帖子,

def post(request, id):
    ....
    ....
    already_liked = PostLikes.objects.filter(user=request.user, post=post).count()
    if number_of_likes > 0:
        already_liked = True # pass this variable to your context
    else:
        already_liked = False # you can make this anything other than boolean

然后通过使用Javascript和{{already_liked}},在模板中更改“喜欢”按钮的动画。