django: form to json

2020-07-18 02:51发布

问题:

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?

回答1:

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?


回答2:

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