jned29 jned29 - 7 days ago 5
Python Question

How to display error messages from form with ajax using python django

I'm trying to display the error messages that I provided on my forms, but it only display the id name instead of error message.

Here's my code

Form.py

class SecurityCode(forms.Form):
sCode = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(id="scode", name="scode", required=True, size=25, placeholder=" Security Code")), error_messages={ 'invalid': "This value must contain only letters, numbers and underscores." })


Views.py

def security(request):
if request.method == 'POST':
securityField = SecurityCode(request.POST)

if taxpayerField.is_valid():
return HttpResponse("success")
else:
return HttpResponse(taxpayerField.errors)


Note: I'm trying to get the error message in this views not on my html because I'm trying to alert that on my javascript. Also this is just my sample code not the original one.

Answer

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.

Comments