django: form to json

。_饼干妹妹 提交于 2020-04-10 03:53:25

问题


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


来源:https://stackoverflow.com/questions/18561585/django-form-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!