Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: form to json

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?

like image 527
rom Avatar asked Sep 01 '13 18:09

rom


People also ask

What is form Is_valid () in Django?

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.

What is form Non_field_errors?

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.

What is form cleaned_data?

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).

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


2 Answers

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) 
  • JsonResponse: https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects
  • Form.cleaned_data: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
  • Form.errors.as_json(): https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors.as_json
like image 114
Bartleby Avatar answered Sep 22 '22 17:09

Bartleby


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:

  • How to cast Django form to dict where keys are field id in template and values are initial values?
like image 43
alecxe Avatar answered Sep 21 '22 17:09

alecxe