[Fixed]-How to display error messages from form with ajax using python django

1👍

You can try this:

views.py:

from django.http import JsonResponse

def security(request):
    form = SecurityCode(request.POST)

    if not form.is_valid():
        return JsonResponse({
            'success': False, 
            'err_code': 'invalid_form', 
            'err_msg': form.errors,
        })

    #[...] Actions if form is valid ...

    return render(request, 'template.html')

javascript code:

def submit_form(){
    var data = {
        field1: '...',
        field2: '...',
        csrfmiddlewaretoken: 'csrftoken',
    };

    $.ajax({
        url: '/submit/form/',
        method: 'POST',
        data: data,
        dataType: 'json',
        success: function (data){
            if (data.success){
                // Actions ...
            }
            else if (data.err_code === 'invalid_form'){
                for(var key in data.err_msg){
                    console.log('[error] for ' + key + ': ' + data.err_msg[key][0]);
                }
            }
        },
    });
}

I use console.log to illustrate the recovery of the error message for each field.

👤Anton

Leave a comment