วันก่อนพยายามจะทำ ajax form validation กับ django ก็ประสบกับปัญหาว่าอยากจะส่ง error กลับมาเป็น json ซึ่งปกติจะใช้ simplejson ทำการ dump ข้อมูลจาก dict ออกมาได้เลย
from django.http import HttpResponse
import simplejson
def json_response(request, obj):
return HttpResponse(simplejson.dumps(obj))
ปกติก็แค่ส่ง dictionary กลับไปก็ใช้ได้ ซึ่งตอนแรกก็เห็นว่า form.errors มันก็เป็น dict เลยใส่ลงไปเลยไม่ได้คิดอะไรมาก ปรากฏว่ามัน Error เพราะว่า form.errors เป็น ErrorDict ซึ่งเก็บ function ของ django อยู่ ทำให้ simplejson ไม่สามารถเอาข้อมูลออกมาได้ เลยจำเป็นต้องแปลงให้เป็น dict ก่อน
def edict_to_dict(edict):
return dict([(key, val) for key, val in edict.iteritems()])
หลังจากนั้นมันก็กลายเป็น dict ธรรมดาส่งไปให้ simplejson ได้เลย