Skip to content
Advertisement

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

When i try to save form without ajax then the error is validation successfully showing. BUT error is not showing in 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 %}

I have tried many times but still not showing the validation error.

Any help would be much Appreciated.

Thank You in Advance.

Advertisement

Answer

The model fields validators are not called automatically on calling 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.

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