如何防止我的网站用户发布包含脏话的帖子?

2024-10-03 19:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Reddit(https://www.reddit.com/r/django/comments/chalnz/how_can_i_prevent_my_site_users_from_publishing/)上看到这个问题,但是在Reddit上共享代码很快就会变得混乱,所以决定在这里共享答案(请看我下面的评论)


Tags: djangofromhttpscommywwwsitecomments
1条回答
网友
1楼 · 发布于 2024-10-03 19:23:08

注意-为了保持Stack Overflow的专业性,我用星号来掩盖一些脏话。对于普通文本(而不是代码),堆栈溢出使用星号来表示需要粗体或斜体格式的文本,因此我在整个帖子中使用星号是不一致的。

forms.py

from blog.models import Comment
from django import forms

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('email', 'body')

def clean_body(self):
    body = self.cleaned_data.get("body")
    if "f**k" in body or "s**t" in body :
        raise forms.ValidationError("No swearing.")
    return body

def clean_email(self):
    email = self.cleaned_data.get("email")
    if not "gmail.com" in email:
        raise forms.ValidationError("Email has to be gmail.com")
    return email

型号.py

class Comment(models.Model):
#The foriegn key is linked to the ID field in the Post model
#id = models.IntegerField(primary_key=True, blank=False)
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
nameid = models.ForeignKey(User,on_delete=models.CASCADE,related_name='commentsid')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField() 
created_on= models.DateTimeField(default = timezone.now())
active = models.BooleanField(default=True)

视图.py

def post_detail(request, pk_slug):
    template_name = 'post_detail.html'



if pk_slug.isdigit():
  post = Post.objects.filter(id=pk_slug).first()
else:
  post = Post.objects.filter(url=pk_slug).first()

comments = Comment.objects.filter(post=post.id ,active=True)
new_comment = None


if request.method == 'POST':



    comment_form = CommentForm(data=request.POST)

    if comment_form.is_valid():

      # Post instance which will be assigned to post attribute in Comment model



      new_comment = comment_form.save(commit=False)
      new_comment.post = get_object_or_404(Post, id=post.id)

      new_comment.name = request.user.username
      new_comment.nameid = request.user
      new_comment.save()

      comment_form=CommentForm()





else:
    comment_form = CommentForm()

return render(request, template_name, {'post': post,
                                       'comments': comments,
                                       'new_comment': new_comment,
                                       'comment_form': comment_form})

更新

切普纳正确地指出了我最初的方法中的一个缺陷,即完全合法的单词,如Scunthorpe(英格兰的一个地方)不会被接受,因为它们包含冒犯性的子字符串。在斯肯索普斯的案例中,请看第2到第5个字母。您可以在此处https://en.wikipedia.org/wiki/Scunthorpe_problem了解有关此问题的更多信息

您可以通过更详细的if语句在一定程度上避免此问题

def clean_body(self):
    body = self.cleaned_data.get("body")
    if not "Scunthorpe" in body: 
        if "c**t" in body:
            raise forms.ValidationError("No swearing.")
    return body

这种方法的另一个问题是它没有考虑到原始帖子中提到的主题。如果原来的帖子是关于厕所的,那么你的网站读者可能会在评论部分合理地使用*hit这个词。如果你打算全面禁止“hit”这个词,你还必须过滤掉故意拼错的单词,比如s*1t(用i代替1)

一个潜在的妥协是,任何可能包含冒犯性语言的评论在发布到网站上之前,都由超级用户手动阅读

def post_detail(request, pk_slug):
    template_name = 'post_detail.html'



if pk_slug.isdigit():
  post = Post.objects.filter(id=pk_slug).first()
else:
  post = Post.objects.filter(url=pk_slug).first()

comments = Comment.objects.filter(post=post.id ,active=True)
#post = Post.objects.get(pk=pk)
new_comment = None

if request.method == 'POST':




    comment_form = CommentForm(data=request.POST)



    if comment_form.is_valid():
      #print(comment_form.cleaned_data)
      # Post instance which will be assigned to post attribute in Comment model

      #post_instance = get_object_or_404(Post, id=post.id)

      new_comment = comment_form.save(commit=False)
      new_comment.post = get_object_or_404(Post, id=post.id)
      if "f**k" in new_comment.body or "s**t" in new_comment.body or "s*1t" in new_comment.body :
        new_comment.active = False
      new_comment.name = request.user.username
      new_comment.nameid = request.user
      new_comment.save()
      print(comment_form)
      comment_form=CommentForm()





else:

相关问题 更多 >