Django评论违规词验证器失效,请求排查问题并解决
评论违规词验证函数故障排查与修复
嘿,我帮你梳理下代码里的几个问题,这些就是导致验证功能失效的核心原因:
1. 违规词文件路径不匹配
你的代码里用了相对路径"badwords.txt",但实际文件在C:\Users\User\Desktop\Project\badwords.txt。如果你的Django项目根目录不在这个路径下,程序根本找不到这个文件。推荐用os模块构建路径,既灵活又避免硬编码:
import os import re from django.core.exceptions import ValidationError from django.db import models from django.contrib.auth.models import User # 动态获取项目根目录路径,适配不同环境 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BADWORDS_FILE = os.path.join(BASE_DIR, 'badwords.txt') # 读取违规词时去掉换行符,同时统一转小写 with open(BADWORDS_FILE, encoding='utf-8') as f: CENSORED_WORDS = [word.strip().lower() for word in f.readlines() if word.strip()]
2. readlines()保留了换行符,导致匹配失效
readlines()会把每行末尾的\n也读进来,比如文件里的"spam"会变成"spam\n",这样自然匹配不到评论里的"spam"。用strip()去掉换行和空白,再转小写可以实现不区分大小写的检测,实用性更强。
3. 变量作用域错误,censored_word无法被引用
你原来用any()的写法里,censored_word是生成器内部的临时变量,在外部的raise语句里根本找不到它,会直接抛出NameError。改成显式循环遍历,找到违规词再抛出错误就没问题了:
def validate_comment_text(text): # 把评论内容转小写,和违规词统一格式 cleaned_text = re.sub("[^\w]", " ", text.lower()) words = set(cleaned_text.split()) for bad_word in CENSORED_WORDS: if bad_word in words: raise ValidationError(f"{bad_word} is censored!")
4. created字段的时间设置错误
auto_now=True会在每次保存评论(比如更新时)都修改这个时间,而created应该只记录评论第一次创建的时间,所以要改成auto_now_add=True:
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_add=True) # 这里修改了参数
把这些修改后,你的验证函数应该就能正常工作了。测试的时候可以试试在评论里输入badwords.txt里的词,看看会不会抛出预期的验证错误~
内容的提问来源于stack exchange,提问作者A_K
相关产品推荐
相关产品推荐

