Using Django Piston with Backbone.js: Better with templatetags?

133 views
Skip to first unread message

olivergeorge

unread,
Mar 10, 2011, 5:03:01 PM3/10/11
to django-piston
Hi Guys

I'm new to Django Piston and Backbone.js but love them both.

Backbone.js does MVC on the client side. It seems to work well with
Django Piston - I've only played with fetching data but it looks good.

Backbone.js encourages data to be embedded in HTML if it's needed when
the page loads. That way there's not a second request to fetch JSON
data as soon as the page loads. That means doing something like this:

<script>HatCollection.refresh({{ Hat.objects.all | jonify }}); </
script>

In order to stay DRY I need a way to call Django Piston Json
serializers from a template. I can't see any obvious way beyond
rolling my own tags but I'd love to avoid boilerplate and bypassing
any permission checking.

Any advice appreciated

cheers, Oliver

Oliver George

unread,
Mar 30, 2011, 7:26:03 PM3/30/11
to django...@googlegroups.com, schickm
Thanks!  I had given thought to that approach.  Reusing the request object does sound a little dangerous.

On 28 March 2011 04:41, schickm <sch...@gmail.com> wrote:
The method that I just discovered is to just simulate the entire
request process.  This doesn't solve your issue of the template tags,
but at least it gives you some way of getting at the generated data.

You need to manually generate the Resource for your handler inside of
whatever view your are rendering your Backbone.js bootstrapping code.

## in your view (this assume you have imported
## piston's Resource and your HatHandler)
def view_func(self, request, ...)
   # ...
   # your regular view code
   # ...
   hat_handler = Resource(HatHandler)
   response = hat_handler(request)
   context['hat_collection'] = response.content
   # ...
   # then the rest of your view code that renders the template
   # ...

## Then in your template
<script>HatCollection.refresh({{ hat_collection }}); </script>


What's important to note is that piston will generate it's json
response with a request that may not have the intended request
parameters you would normally have (like say a specified Hat id), so
this doesn't work for all situations.  To solve that would require
modifying the request object to add certain parameters, which should
be doable.
--
You received this message because you are subscribed to the Google Groups "django-piston" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-pisto...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-piston?hl=en.


schickm

unread,
Mar 27, 2011, 1:41:04 PM3/27/11
to django-piston
Reply all
Reply to author
Forward
0 new messages