I am trying to serialize my form into the json format. My view:
form = CSVUploadForm(request.POST, request.FILES)
data_to_json={}
data_to_json = simplejson.dumps(form.__dict__)
return HttpResponse(data_to_json, mimetype='application/json')
I have the error <class 'django.forms.util.ErrorList'> is not JSON serializable
. What to do to handle django forms?
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
non_field_errors () This method returns the list of errors from Form. errors that aren't associated with a particular field. This includes ValidationError s that are raised in Form. clean() and errors added using Form.
form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
Just in case anyone is new to Django, you can also do something like this:
from django.http import JsonResponse
form = YourForm(request.POST)
if form.is_valid():
data = form.cleaned_data
return JsonResponse(data)
else:
data = form.errors.as_json()
return JsonResponse(data, status=400)
You may want to look at the package called django-remote-forms:
A package that allows you to serialize django forms, including fields and widgets into Python dictionary for easy conversion into JSON and expose over API
Also see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With