表单验证在Ajax表单提交中不起作用



我正在构建一个具有评论功能的小型博客应用程序,因此,我试图在评论中阻止bad words。(如果有人试图添加所选的脏话,则会引发错误(。

但当我在model field中添加text validation并尝试输入坏字时,它正在保存,而没有显示validation的任何错误。

当我尝试在没有ajax的情况下保存表单时,错误是验证成功显示。但是ajax中并没有显示错误。

型号.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 %}

我已经尝试了很多次,但仍然没有显示验证错误。

任何帮助都将不胜感激。

提前谢谢。

在调用save时不会自动调用模型字段验证器。您需要调用以下方法之一:full_cleanclean_fieldsvalidate_unique,如文档的验证对象部分所述。

如果我们使用模型形式,这些方法通常会被调用,这大大简化了这个过程。我强烈建议使用一个。如果您想更改当前代码,可以执行以下操作,保存实例:

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()

最新更新