Comments moderation is a must for every high user activity blog. Unlike in a WordPress blog where you can install a plugin for comments, if you're using a custom system like Django for a blog then you have to build that moderation from scratch. This piece helps you set up comments moderation, filtering vulgar and inappropriate language from comments.
Vulgar words model
Create a model that'll store all the phrases and words you don't want in your comments. You can find plenty of vulgar words online and import them into your database.
class InappropriateWord(models.Model):
word = models.CharField(_("Word"), max_length=255)
class Meta:
verbose_name = _("Inappropriate Word")
verbose_name_plural = _("Inappropriate Words")
def __str__(self):
return self.word
Filter function
This function will help filter every input from the users and clean all inappropriate/vulgar words and replace them with ****.
import re
def clean_inappropriate(body):
new_body = body
offensive = InappropriateWord.objects.all()
for item in offensive.iterator():
if item.word in new_body:
pattern = re.compile(item.word, re.IGNORECASE)
new_body = pattern.sub("****", new_body)
return new_body
Usage
Now in your comments model, override the save function and filter the body of the comment.
class Comment(models.Model):
article = models.ForeignKey(
Article, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(
Profile, on_delete=models.CASCADE, related_name='comments')
parent = models.ForeignKey(
'self', null=True, related_name='replies', on_delete=models.CASCADE)
body = models.TextField(_("Your Comment"))
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
def save(self, *args, **kwargs):
self.body = clean_inappropriate(self.body)
super(Comment, self).save(*args, **kwargs)
Now add the words you don't want to see in the comments. Remember to register the InappropriateWord model in the admin.
Happy coding.