I have described a general implementation for validating ajax forms in this answer. This was in the context of validating form fields as they are being entered (i.e. prior to form submission), but the same idea applies when the form is finally submitted.
Your render_field()
macro is written to render field errors server-side. But your POST
request does not re-render the form, it just returns the result of a calculation. You really never give a chance to the server to re-render or update the form.
The easiest solution is to not use ajax for the form submission. Then when you get a POST request you validate, and return a new page back to the client. To render that page you will pass the form (which will have any validation errors in it) and the result of your calculation.
If you want to continue with ajax submission then you need to figure out a strategy to update the form in the client. Here are some ideas:
- your JSON response must include any validation errors, so you will need to copy them from the form object into the JSON dictionary.
- your ajax success handler not only needs to update the HTML of
#result
but also needs to insert any validation errors into the DOM in the proper place. - your
render_field()
macro cannot render error messages because at the time this macro runs the errors are not known yet. Instead you should just create empty and invisible elements that can hold the errors, and these will be populated by the client in the ajax submission callback.
I hope this helps.