26π
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()] })
37π
This appears to have been improved. The following works in Django 1.3:
return json_response({
'success': False,
'errors': dict(form.errors.items()),
})
No need for __unicode__
or lazy translation any more. This also gives a full array of errors for each field.
- [Django]-Django: Redirect to previous page after login
- [Django]-Django admin default filter
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
32π
For Django 1.7+ use Form.errors.as_json() or something like this:
errors = {f: e.get_json_data() for f, e in form.errors.items()}
return json_response(success=False, data=errors)
- [Django]-Django 1.8 migrate is not creating tables
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
- [Django]-How to set current user to user field in Django Rest Framework?
4π
The issue here is that error message are lazy translation object.
The docs do mention this:
Just make sure youβve got ensure_ascii=False and use a LazyEncoder.
- [Django]-How to completely uninstall a Django app?
- [Django]-How can I tell the Django ORM to reverse the order of query results?
- [Django]-Authorization Credentials Stripped β django, elastic beanstalk, oauth
1π
We can do this:
import simplejson as json
errors = json.dumps(form.errors)
return HttpResponse(errors, mimetype='application/json')
- [Django]-Django import error β No module named core.management
- [Django]-Reload django object from database
- [Django]-Users in initial data fixture
1π
json.dumps
canβt serialize djangoβs proxy function (like lazy translations).
As documented you should create a new Encoder class:
import json
from django.utils.functional import Promise
from django.utils.encoding import force_text
from django.core.serializers.json import DjangoJSONEncoder
class LazyEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Promise):
return force_text(obj)
return super(LazyEncoder, self).default(obj)
Use the new Encoder like this:
json.dumps(s, cls=LazyEncoder)
Thatβs all π
- [Django]-How to reset db in Django? I get a command 'reset' not found error
- [Django]-How to group by AND aggregate with Django
- [Django]-How to change status of JsonResponse in Django
1π
You should use django in built method.
from django.http import JsonResponse
return JsonResponse(form.errors.as_json())
- [Django]-How can I list urlpatterns (endpoints) on Django?
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-ImageField overwrite image file with same name
1π
I solved it using get_json_data()
as follows:
data = form.errors.get_json_data()
return JsonResponse(data, status=400, safe=False)
We get a valid json:
{"amount": [{"message": "Ensure this value is greater than or equal to 100.", "code": "min_value"}]}
See: https://docs.djangoproject.com/en/4.1/ref/forms/api/#django.forms.Form.errors.get_json_data
If we use as_json()
like this:
data = form.errors.as_json()
return JsonResponse(data, status=400, safe=False)
We get a string formatted as a json:
"{\"amount\": [{\"message\": \"Ensure this value is greater than or equal to 100.\", \"code\": \"min_value\"}]}"
- [Django]-Django 1.4 β can't compare offset-naive and offset-aware datetimes
- [Django]-How do I raise a Response Forbidden in django
- [Django]-Django error message "Add a related_name argument to the definition"