backbone.jsmustachetastypieicanhaz.js

backbone.js translate django server template with backbone collection


I am used to defining my django views with http request that send http response back with a python dictionary of data that i can iterate over and display. I am attempting to replace this with the use of backbone.js.

Currently i have a set up like so:

<ul id="teaching_students">

 {% for student in students.object_list %}
    <li class="selected">
      <span> {{ student.name }} </span>
    </li>
 {% endfor %}
</ul>

and i would like to use ICanHaz.js and Mustache.js as javascript templates to fill {{ student.name}} on the client side.

Using tastypie so far, i have a PersonResource which has all the students coming back as json objects when the following url is passed.

http://127.0.0.1:8000/api/people/?format=json
  1. Do i need to generate an API view for this url in views.py, if so what does that look like?
  2. How do i call, in backbone.js, this url and set up a collection, view and a correct route ?

My client side structure is broken down into views/models (i use require.js to bring them together).

I am using several plugins to help bridge the gap between backbone and tastypie (backbone-tastypie.js) but i really want to see how others have replaced traditional django template rendering with REST api's and backbone.js

EDIT: Adding Backbone model, here is the model i am using

define([
    'underscore',
    'backbone'
], function(_, Backbone) {

    var PersonModel = Backbone.Model.extend({

        defaults : {

        },

        initialize: function( options ) {

        },

        parse : function(res) {
            // because of jsonp
            return res.data;
        }

    });

    return PersonModel;

});

Solution

  • So you want to move from server side rendering to client side rendering? This means you incur additional http requests. But it's possible.

    Do i need to generate an API view for this url in views.py, if so what does that look like?

    Tasty pie does all the work once you've specified your ModelResource and urlpattern. There's no need for you to have another function in your app's views.py to handle the http request-response cycle.

    1. Check out the tasty pie tutorial to learn how to hook your resource to a url.
    2. Use a test REST client like the Postman chrome extension to see if everything's ok.

    How do i call, in backbone.js, this url and set up a collection, view and a correct route ?

    1. Treat the api like any other. Set up the url field of your model to

      /api/people/?format=json

    2. Have your view listen to the change event of PersonModel

    3. Fetch the model.

    4. Render the view using the templating engine of your choice when the data is received.

    Also see Adding REST to Django for options on providing RESTful interfaces to django apps.