Anmol Gulati
Anmol Gulati

Reputation: 83

Return django validation errors in JSON format

Suppose I am building a registration/signup or any form in general for my web app in Django and I want the same form for Web/Android/IOS. So I want the frontend and backend(Django) to communicate via JSON. My question is how can I send validation errors in JSON format if the user on any platform(Web/Android/IOS) gives me invalid data like "the email already exists" type of errors?

I need the best way possible to handle this type of scenarios and well-detailed example/explanation will be much appreciated.

Thank You.

Upvotes: 2

Views: 1299

Answers (1)

Alasdair
Alasdair

Reputation: 308829

The form's errors attribute has an as_json method you can use.

if form.is_valid():
    # process valid form
else:
    errors_json = form.errors.as_json()
    ...

Note the warning in the docs about escaping the errors to avoid cross site scripting attacks.

Upvotes: 3

Related Questions