python - 如何审查 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']))
解决方案
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])
推荐阅读
- android - Mapbox Android Marker 已弃用 API 21+
- php - 为什么 nginx 在我的 PHP 文件下载时返回 403?
- asp.net - 在 Angular 7 中的 http post 后显示数据
- javascript - JQuery/Javascript:新的 RegExp() 停止循环
- c# - 部分视图以整页形式返回
- java - 如何获取 Arraylist 中的 Hashmap 值
- html - 为什么我的动画属性在 CSS 中不起作用
- php - 使用 Symfony Validation 组件根据给定数组中的键验证特定的数组结构
- mongodb - E11000 duplicate key error even if inserted values for the unique field are different
- c# - 如何更改自动更新器的逻辑?