Reputation: 31161
I have a query set whose objects I'd like to use to populate a template. One view I have ends with
return render_to_response('entry.json', {'entry_list':r}, mimetype="application/json; charset=utf-8")
However I'd like to be able to serialise to json with a template like this without having to return a HTTPResponse. In pseudocode, this might be:
render('entry.json', {'entry_list':r}) #returns a string with the template entry.json
Is this possible? If so, how?
Upvotes: 1
Views: 3970
Reputation: 55962
Django provides a built in shortcut for this.
https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut
I don't quite understand what you are trying to accomplish, But you can just return JSON as your HTTPResponse. You can serialize objects to jason and return it without the use of any template.
Upvotes: 3
Reputation: 164139
What @HankGay said is correct, though you sometimes might want to get the template response with out returning a HttpResponse, even though you are using Django correctly.
read this: Rendering a context:
>>> from django.template import Context, Template
>>> t = Template("My name is {{ my_name }}.")
>>> c = Context({"my_name": "Adrian"})
>>> t.render(c)
"My name is Adrian."
>>> c = Context({"my_name": "Dolores"})
>>> t.render(c)
"My name is Dolores."
Is that what you're after?
Upvotes: 5
Reputation: 71939
If you aren't handling HTTP requests, it doesn't make much sense to use Django, honestly. Look into Jinja 2 for a simple template engine that has lots in common w/ Django's, and SQLAlchemy for an ORM that is equal or better than Django's.
Upvotes: 0