返回

架起沟通桥梁—— HelloDjango 评论功能详解

见解分享

HelloDjango 系列教程:第 14 篇——交流的桥梁“评论功能”

到目前为止,我们的 Django 博客文章展示部分已经接近尾声。然而,这仅仅是旅程的开始,HelloDjango 系列文章的重点在于创建一个精简而全面的博客系统。在后续的文章中,我们将逐步完善博客系统,使其功能更加齐全,让用户获得更好的使用体验。

在这篇文章中,我们将向你展示如何为你的 Django 博客添加评论功能。评论功能是博客系统的重要组成部分,它可以促进读者与博主之间的交流,提高用户体验。我们将详细介绍如何在 Django 中实现评论功能,包括评论的发表、审核、回复、通知、点赞和排序等功能。此外,还将介绍如何管理评论,包括评论的黑名单和精华评论的设置。通过本教程,你将能够为你的博客系统添加一个功能齐全的评论系统。

前言

评论功能是博客系统的重要组成部分,它可以促进读者与博主之间的交流,提高用户体验。在 Django 中实现评论功能相对简单,但需要注意一些细节,以确保评论功能的稳定性和安全性。

实现评论功能

  1. 在 Django 模型中添加 Comment 模型
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
  1. 在 Django 视图中添加评论发表、审核、回复等功能
def post_detail(request, post_id):
    post = get_object_or_404(Post, pk=post_id)
    comments = Comment.objects.filter(post=post, is_approved=True).order_by('-created_time')

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            comment.post = post
            comment.author = request.user
            comment.save()
            return redirect('post_detail', post_id=post_id)
    else:
        comment_form = CommentForm()

    context = {
        'post': post,
        'comments': comments,
        'comment_form': comment_form,
    }
    return render(request, 'blog/post_detail.html', context)
  1. 在 Django 模板中添加评论展示、回复等功能
{% for comment in comments %}
    <div class="comment">
        <div class="comment-author">
            {{ comment.author.username }}
        </div>
        <div class="comment-content">
            {{ comment.content }}
        </div>
        <div class="comment-meta">
            <a href="{% url 'post_detail' comment.post.id %}#comment-{{ comment.id }}">回复</a>
        </div>
    </div>
{% endfor %}

{% if comment_form %}
    <form action="{% url 'post_detail' post.id %}" method="post">
        {% csrf_token %}
        {{ comment_form.as_p }}
        <input type="submit" value="发表评论" />
    </form>
{% endif %}

管理评论

  1. 在 Django 管理员中添加评论管理页面
class CommentAdmin(admin.ModelAdmin):
    list_display = ('post', 'author', 'content', 'created_time', 'is_approved')
    list_filter = ('post', 'author', 'is_approved')
    search_fields = ('content',)
    actions = ['approve_comments', 'delete_comments']

    def approve_comments(self, request, queryset):
        queryset.update(is_approved=True)

    approve_comments.short_description = "Approve selected comments"

    def delete_comments(self, request, queryset):
        queryset.delete()

    delete_comments.short_description = "Delete selected comments"
  1. 在 Django 视图中添加评论黑名单和精华评论设置功能
def comment_settings(request):
    blacklisted_users = User.objects.filter(is_blacklisted=True)
    精华评论 = Comment.objects.filter(is_精华=True)

    if request.method == 'POST':
        blacklisted_users_form = BlacklistedUsersForm(request.POST)
        精华评论_form = 精华评论Form(request.POST)

        if blacklisted_users_form.is_valid():
            blacklisted_users = blacklisted_users_form.cleaned_data['blacklisted_users']
            User.objects.filter(username__in=blacklisted_users).update(is_blacklisted=True)

        if 精华评论_form.is_valid():
            精华评论 = 精华评论_form.cleaned_data['精华评论']
            Comment.objects.filter(pk__in=精华评论).update(is_精华=True)

    else:
        blacklisted_users_form = BlacklistedUsersForm()
        精华评论_form = 精华评论Form()

    context = {
        'blacklisted_users': blacklisted_users,
        '精华评论': 精华评论,
        'blacklisted_users_form': blacklisted_users_form,
        '精华评论_form': 精华评论_form,
    }
    return render(request, 'blog/comment_settings.html', context)

总结

评论功能是博客系统的重要组成部分,它可以促进读者与博主之间的交流,提高用户体验。在 Django 中实现评论功能相对简单,但需要注意一些细节,以确保评论功能的稳定性和安全性。通过本教程,你已经能够为你的博客系统添加一个功能齐全的评论系统。在后续的文章中,我们将继续完善博客系统,使其功能更加齐全,让用户获得更好的使用体验。