Returning pure Django form errors in JSON

前端 未结 6 2021
青春惊慌失措
青春惊慌失措 2020-12-12 16:50

I have a Django form which I\'m validating in a normal Django view. I\'m trying to figure out how to extract the pure errors (without the HTML formatting). Below is the code

6条回答
  •  感动是毒
    2020-12-12 17:49

    Got it after a lot of messing around, testing different things. N.B. I'm not sure whether this works with internationalization as well. This also takes the first validation error for each field, but modifying it to get all of the errors should be rather easy.

    return json_response({ 'success' : False,
                           'errors' : [(k, v[0].__unicode__()) for k, v in form.errors.items()] })
    

提交回复
热议问题