javascript - 表单验证在 Ajax 表单提交中不起作用
问题描述
我正在构建一个具有评论功能的小型博客应用程序,所以我试图阻止bad words
评论。(如果有人尝试添加选定的坏词,则会引发错误)。
但是当我添加 text validation
并model field
尝试输入坏词时,它会保存而不显示任何错误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)
视图.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_clean
, clean_fields
,validate_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()
推荐阅读
- javascript - 如何在 WPforms 中选择特定日期
- ckeditor4.x - 如何在 stenciljs 中添加 npm ckeditor4?
- rundeck - 如何在 Rundeck 上为列表中的每个用户运行作业?
- python - Python 使用 mne 读取 EEG 数据形式的 .csv 文件?
- vue.js - 错误消息快速显示然后在 VUE 中按预期隐藏
- sharepoint - 在 Power Automate 中创建频道时如何自动创建文件夹和文件?
- php - 502 错误网关 nginx/1.19.1
- android - 如何阻止 Android Studio AVD 模拟器崩溃
- xgboost - 具有多种输入类型的 Onnx 模型转换
- react-native - 如何构建忽略基于 Web 的组件的移动应用程序代码?