Skip to content

Instantly share code, notes, and snippets.

@ajamaica
Created June 23, 2011 18:09
Show Gist options
  • Save ajamaica/1043156 to your computer and use it in GitHub Desktop.
Save ajamaica/1043156 to your computer and use it in GitHub Desktop.
View : Model to Json
from django.forms.models import model_to_dict
from django.utils.simplejson import dumps, JSONEncoder
from django.utils.encoding import force_unicode
#Model es tu modelo y esto es un view
def model_to_json(request):
try:
model_id = request.GET["model_id"]
model = Model.objects.get(pk=model_id)
except:
raise Http404
prospect_dict=model_to_dict(model)
model_dict=prospect_dict
for key, value in model_dict.items():
if key.startswith('_'):
del model_dict[key]
else:
model_dict[key] = force_unicode(value)
json_response = dumps(model_dict, ensure_ascii=False, indent=2)
return HttpResponse(json_response,mimetype="text/javascript")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment