Django Tastypie & Backbone.js: how to programmatically get a list of objects to load bootstrapped models

Official recipe “Using Your Resource In Regular Views” is a bit outdated and doesn’t cover the case when a list of objects must be retrieved.

So I looked at Resource.get_list() implementation and came up with this code for my Django view:

def list(request):
    # use API to load bootstrapped model data into HTML
    res = NoteResource()
    request_bundle = res.build_bundle(request=request)
    queryset = res.obj_get_list(request_bundle)

    bundles = []
    for obj in queryset:
        bundle = res.build_bundle(obj=obj, request=request)
        bundles.append(res.full_dehydrate(bundle, for_list=True))

    json = res.serialize(None, bundles, "application/json")

    return render(request, "notes/note_list.html", {"notes_json": json})

And this is how I use it with Backbone.js to load my model data from JSON as recommended in Backbone FAQ:

    var json = "{{notes_json|escapejs}}";
    var bootstrapped_notes = JSON.parse(json);
    var AppView = Backbone.View.extend({
        initialize: function() {
            // ...


Adding escapejs filter should (hopefully) protect against XSS attacks, e.g. adding “</script>” somewhere in model field.

I’ve also proposed 2 pull requests for fixing Tastypie docs:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s