Join Login Create a Request

Comments Moderation for a Django Blog

|
Comments Moderation for a Django Blog

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.


Tags.




Recent Posts

How to use robot.txt on a Django Website
How to use robot.txt on a Django Website
How to add a robots.txt file on a Django website so that you..
Read More
Top sites for remote jobs
Top sites for remote jobs
Where to find remote jobs for software developers in 2022...
Read More
Project ideas for a software developer portfolio
Project ideas for a software developer portfolio
Projects which can strengthen your portfolio as a software d..
Read More
My case for WordPress
My case for WordPress
WordPress strengths and weaknesses. When you should use Word..
Read More