rom
rom

Reputation: 3672

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?

Upvotes: 9

Views: 22072

Answers (2)

Bartleby
Bartleby

Reputation: 1429

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) 

Upvotes: 10

alecxe
alecxe

Reputation: 474281

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:

Upvotes: 6

Related Questions