我正在构建一个具有评论功能的小型博客应用程序,因此,我试图阻止评论中出现 bad words
。 (如果有人试图添加选定的坏词,则会引发错误)。
但是当我在 text validation
中添加 model field
并尝试输入坏词时,它会保存而不显示任何 validation
错误。
当我尝试在没有 ajax 的情况下保存表单时,错误是验证成功显示。但错误未在 ajax 中显示。
models.py
class Comment(models.Model):
description = models.CharField(max_length=20000, null=True, blank=True,validators=[validate_is_profane])
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
views.py
def blog_detail(request, pk, slug):
data = get_object_or_404(Post, pk=pk)
comments = Comment.objects.filter(
post=data)
context = {'data':data,'comments':comments}
return render(request, 'mains/blog_post_detail.html', context)
if request.GET.get('action') == 'addComment':
if request.GET.get('description') == '' or request.GET.get(
'description') == None:
return None
else:
comment = Comment(description=request.GET.get('description'),
post=data,
user=request.user)
comment.save()
return JsonResponse({'comment': model_to_dict(comment)})
blog_post_detail.html
{% for comment in comments %}
{{comment.comment_date}}
<script>
document.addEventListener('DOMContentLoaded', function () {
window.addEventListener('load', function () {
$('#commentReadMore{{comment.id}}').click(function (event) {
event.preventDefault()
$('#commentDescription{{comment.id}}').html(
`{{comment.description}}`)
})
})
})
</script>
{% endfor %}
我已经尝试了很多次,但仍然没有显示验证错误。
任何帮助将不胜感激。
提前致谢。
答案 0 :(得分:0)
模型字段验证器不会在调用 save
时自动调用。您需要调用以下方法之一来执行此操作:full_clean
、clean_fields
、validate_unique
,如文档的 Validating objects 部分所述。
这些方法通常由 model form 调用(如果我们正在使用),大大简化了这个过程。我强烈建议使用一个。但是,如果您想更改当前代码,可以执行以下操作,保存实例:
from django.core.exceptions import ValidationError
comment = Comment(
description=request.GET.get('description'),
post=data,
user=request.user
)
try:
comment.full_clean() # Perform validation
except ValidationError as ex:
errors = ex.message_dict # dictionary with errors
# Return these errors in your response as JSON or whatever suits you
comment.save()