我正在构建一个具有评论功能的小型博客应用程序,因此,我试图阻止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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句