Saturday, March 12, 2011

Re: Rendering JSON from Django Views

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)

iQEcBAEBAgAGBQJNe6R2AAoJEALmHhtvR0Guk8MIANPQdmFqvrHzyX33ymU/DmkJ
T4EOSw7b/L4FIMKtLBEIsrKDVtMdgIDF+rQ6uZnUkRl98bq87rbWudQBYKZPSOnr
tlxKdBoiyz0eULom05xuDiimkU2YoOzecMGICcGc0RSS5zeINZF+XNorZR4O4aCF
hS3uu7UVS8ecIzDhGI+CQirwSRJA/AMHRP+BnKp/6/Yjml6mFFAYgVU/Sa/whLqR
k1SkccXapNmBquYxGCv7oDy4fg77aZYvlBV7MSAWJcDQBEu9gStk3aZLWT2mOPne
fxwkhX0+HlEWwv1pK0QMNIPBbgqanIeO0YnnDCLdRY7Rh/YNsN2P5F3Md+au7TE=
=uq5O
-----END PGP SIGNATURE-----
El 12/03/11 13:31, yongzhen zhang escribió:
> Hi, i want to rendering JSON from Django views, here is my models:
> class Continent(models.Model):
> name = models.CharField(max_length='10',unique=True)
> code = models.CharField(max_length='5',unique=True)
> class Country(models.Model):
> name = models.CharField(max_length='10',unique=True)
> code=models.CharField(max_length='10',unique=True)
> continent=models.ForeignKey('Continent')
> ###############here is my views.py#######################
> from django.http import Http404
> from django.shortcuts import render_to_response, get_object_or_404
> from django.utils import simplejson as json
> from models import Continent, Country
>
> def continent_json(request, continent_code):
> continent=get_object_or_404(Continent, code=continent_code)
> if not continent:
> raise Http404("Not implemented")
> context = {"all_contries":
> Country.objects.filter(continent=continent.id)}
> data=json.dumps(context)
> return render_to_response(data, mimetype="application/json")
>
> I want to get the result when the continent_code=eu:
> {
> "xk": "Kosovo",
> "ch": "Switzerland",
> "gr": "Greece",
> "va": "Vatican City",
> "ee": "Estonia",
> "is": "Iceland",
> "al": "Albania",
> "gg": "Guernsey",
> }
> There is some problems with my views.py file. Anybody know how to
> modify my views.py?
>

try with this view

def continent_json(request, continent_code):
continent=get_object_or_404(Continent, code=continent_code)
if not continent:
raise Http404("Not implemented")
context = [{'code': i.code, 'continent': i.name } for i in
Country.objects.all() ]
data=simplejson.dumps(context)
return render_to_response(data, mimetype="application/json")
--
Ezequiel Marquez

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate