Display form errors with django and ajax Display form errors with django and ajax ajax ajax

Display form errors with django and ajax


as an example

django form returns errors with json format using form.errors.as_json(). assume:

{    "sender": [         {           "message": "Enter a valid email address.",            "code": "invalid"         }    ],    "subject": [          {            "message": "This field is required.",             "code": "required"          }    ]}

after that, ajax get a response (in success: function(data) {}. assume already become an object:

    data = {    "sender": [    {        "message": "Enter a valid email address.",       "code": "invalid"    },    {        "message": "Enter a .",       "code": "invalid"    }  ],    "subject": [    {        "message": "This field is required.",       "code": "required"    }  ]};

and you're already renders previous form, assume:

<input type="text" name="sender"> <br><input type="text" name="subject"> <br><button>Submit</button>

and to render these messages, you can write scripts in the click events:

// in ajax success (event click)if ($("input").next('p').length) $("input").nextAll('p').empty();    for (var name in data) {    for (var i in data[name]) {      // object message error django      var $input = $("input[name='"+ name +"']");      $input.after("<p>" + data[name][i].message + "</p>");    }  }

simulation example:

// simulation example, Data obtained from ajax responsevar data = {	"sender": [  	{    	"message": "Enter a valid email address.",       "code": "invalid"    },    {    	"message": "Enter a .",       "code": "invalid"    }  ],	"subject": [  	{    	"message": "This field is required.",       "code": "required"    }  ]};$("button").on("click", function() {	if ($("input").next('p').length) $("input").nextAll('p').empty();	for (var name in data) {    for (var i in data[name]) {      // object message error django      var $input = $("input[name='"+ name +"']");      $input.after("<p>" + data[name][i].message + "</p>");    }  }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" name="sender"> <br><input type="text" name="subject"> <br><button>Submit</button>