horse
horse

Reputation: 501

Display ValidationError In Ajax

I'm trying to display ValidationErrors using ajax. I've read many posts about this and tried many things but can't get it to work. I thiiinnnkkk ValidationErrors are passed as a dictionary and that they need to have json.dumps or .as_json() called on them before they are passed to ajax.

Here is some of my code:

forms.py

raise forms.ValidationError('Please enter a number greater than 100')

views.py

if form.is_valid():
    [...]
else:
    # i've tried this
    error_dict= {'status':'form-invalid','form-errors':form.errors}
    return HttpResponse(json.dumps(error_dict),content_type="application/json", status_code=400)
    # and this
    data = {'error':form.errors.as_json(), 'is_valid': False}
    return JsonResponse(data, status_code=400)
    # and more

ajax

error: function (data, xhr, errmsg, err) {
    $('.error').html(data.form-errors)
},

--edit--

console.log:

{error: {…}, is_valid: false}
    error:
        __all__: Array(1)
            0: "You cannot lock a lesson when the following lesson is unlocked"
            length: 1
          __proto__: Object

Upvotes: 1

Views: 287

Answers (1)

Achuth Varghese
Achuth Varghese

Reputation: 2451

The error details are actually store in data['error'] not data.form-errors. You data will also have another item is_valid. The response data structure can be inspected by console logging data in ajax error. According to the structure access values and assign to elements.

In ajax error:

error: function (data, xhr, errmsg, err) {
    console.log(data)
    console.log(data.responseJSON)

    // according to the structure of data access error value and assign
    $('.error').html(data['error'])
},

in views.py form.errors should be passed. in JsonResponse() we need to pass a dictionary.

The first parameter, data, should be a dict instance. doc

if form.is_valid():
    [...]
else:
    data = {'error':form.errors, 'is_valid': False}
    return JsonResponse(data, status_code=400)

In your script if you console.log('data.responseJSON') you could see something like this

enter image description here

In the above image I can access the error message for the field 'fname' as data.responseJSON.error.fname[0]

Upvotes: 2

Related Questions