Friday 20 November 2020

Using Validators in Django not working properly

I have recently learning about Validators and how they work but I am trying to add a function to my blog project to raise an error when a bad word is used. I have a list of bad words in a txt and added the code to be in the models.py the problem is that nothing is blocked for some reason I am not sure of. Here is the models.py

def validate_comment_text(text):

with open("badwords.txt") as f:
    CENSORED_WORDS = f.readlines()

    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!")


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, validators=[validate_comment_text])
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now=True)


from Using Validators in Django not working properly

No comments:

Post a Comment