Question

I am working on form validation with AJAX using Dajax in a Django project. I would like to know whether there is an efficiently way to display validation errors. For now, I return errors in the server-side when AJAX is called, and the client-side displays the errors using javascript.

# (if the form is not valid ...)

error_messages = []
# Display error messages.
for field in form:
    error_messages += field.errors

dajax.add_data({'msg':error_messages}, 'displayError')     
return dajax.json()

Is there any way to use django template tags to display errors using AJAX?

Was it helpful?

Solution

You can return html that represents these errors and just insert it using javascript, something like:

View

template = 'errors.html'
data = {
    'error_messages': error_messages,
}
return render_to_response(template, data,
    context_instance = RequestContext(request))

errors.html

<ul>
{% for message in error_messages %}
    <li>{{ message }}</li>
{% endfor %}
</ul>

Though I'm not a fan of this approach, I prefer separating data and presentation, and usually return only json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top