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:

@active_and_login_required
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:

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

            this.model.reset(bootstrapped_notes);
        }
    });

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:

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s