首页 > 解决方案 > 如何审查 Django 博客评论中的单词?

问题描述

我在我的博客中应用了一个评论系统,我想应用一个简单的代码来审查内容中的坏词。我有一个 badwords.txt ,其中包含所有坏词,可用作字典来审查该词。

我的问题是我不知道应该在哪里应用此代码?

第二,由于使用了这些词,我想知道如何将表单返回为无效

这是坏话代码

import fileinput

filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")

for line in fileinput.input(filename, inplace=True):
    line = line.replace(censor, 'CENSORED')
    print(line, end='')

这是我正在处理的 Django 项目 这是 models.py

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)

这是views.py

class PostDetailView(DetailView):
    model = Post
    template_name = "blog/post_detail.html"  # <app>/<model>_<viewtype>.html

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        comments = Comment.objects.filter(
            post=post).order_by('-id')

        if self.request.method == 'POST':
            comment_form = CommentForm(self.request.POST or None)
            if comment_form.is_valid():
                content = self.request.POST.get('content')
                comment_qs = None

                comment = Comment.objects.create(
                    post=post, user=self.request.user, content=content)
                comment.save()
                return HttpResponseRedirect("blog/post_detail.html")
        else:
            comment_form = CommentForm()

        context["comments"] = comments
        context["comment_form"] = comment_form
        return context

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        self.object.incrementViewCount()
        return res

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = CommentForm

    def form_valid(self, form):
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        form.instance.user = self.request.user
        form.instance.post = post
        return super().form_valid(form)

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug']))

标签: pythondjango

解决方案


Django 有一个称为验证器的功能,您可以使用它来确保评论不包含任何被审查的词。

你可能想要一些被删减的单词列表,你可以从文件中读取:

with open("badwords.txt") as f:
    CENSORED_WORDS = f.readlines()

您可以拥有这样的验证器功能:

import re

def validate_comment_text(text):
    words = set(re.sub("[^\w]", " ",  text).split())
    if any(censored_word in words for censored_word in CENSORED_WORDS):
        raise ValidationError(f"{censored_word} is censored!")

在您的Comment课程中,您可以使用此验证器:

    content = models.TextField(max_length=300, validators=[validate_comment_text])

推荐阅读