簡體   English   中英

如何防止我的網站用戶發布包含臟話的帖子?

[英]How can I prevent my site users from publishing posts that contain swear words?

我在 Reddit 上看到了這個問題( https://www.reddit.com/r/django/comments/chalnz/how_can_i_prevent_my_site_users_from_publishing/ )但是在 Reddit 上分享代碼很快就會變得一團糟,所以決定在這里分享答案(看看我下面的評論)。

注意 - 為了保持 Stack Overflow 的專業性,我使用星號來掩蓋一些臟話。 對於普通文本(但不是代碼),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})

更新

Chepner 正確地指出了我最初的方法中的一個缺陷,即完全合法的單詞,如 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:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM