简体   繁体   English

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

[英]Form validation is not working in Ajax form submitting

I am building a small Blog App with comment Functionality so, I am trying to prevent bad words in comments.我正在构建一个具有评论功能的小型博客应用程序,因此,我试图防止评论中出现bad words ( If anyone tries to add selected bad words then the error will raise ). (如果有人试图添加选定的坏词,则会引发错误)。

BUT when i add text validation in model field and try to enter bad word then it is saving without showing any errors of validation .但是当我在model field添加text validation并尝试输入坏词时,它会保存而不显示任何validation错误。

When i try to save form without ajax then the error is validation successfully showing.当我尝试在没有 ajax 的情况下保存表单时,错误是验证成功显示。 BUT error is not showing in ajax.但是错误未在 ajax 中显示。

models.py模型.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视图.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 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 %}

I have tried many times but still not showing the validation error.我已经尝试了很多次,但仍然没有显示验证错误。

Any help would be much Appreciated.任何帮助将非常感激。

Thank You in Advance.先感谢您。

The model fields validators are not called automatically on calling save .调用save不会自动调用模型字段验证器。 You need to call one of the following methods to do that: full_clean , clean_fields , validate_unique as described in the section Validating objects of the documentation.您需要调用以下方法之一来执行此操作: full_cleanclean_fieldsvalidate_unique ,如验证文档的对象部分中所述。

These methods are normally called by the model form if we are using one, greatly simplifying this process.如果我们使用这些方法,通常由模型表单调用,大大简化了这个过程。 I would highly recommend using one.我强烈建议使用一个。 If you want to change your current code though, you can do the follows, where you are saving the instance:但是,如果您想更改当前代码,您可以执行以下操作,在其中保存实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM