[Django]-Django and backbone.js questions

21đź‘Ť

âś…

you can point backbone collections/models toward whatever urls you want and parse the response however you want in your backbone “subclasses”.

Model.url:

http://documentcloud.github.com/backbone/docs/backbone.html#section-43

Collection.parse:

http://documentcloud.github.com/backbone/docs/backbone.html#section-69

You can setup one-off request handlers that can return some json for backbone to parse/ingest without piston or tastypie. But, yes, these are two good solutions for comprehensive REST with django.

There are some good tips here: http://joshbohde.com/blog/backbonejs-and-django for using backbone with tastypie.

With tastypie, you can limit access to the api with custom authorization/authentication.

http://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html

You can create an Authorization scheme that makes sure that the objects list is filtered to be only the object which the user “owns”, something like this:

class PerUserAuthorization(Authorization):
  def apply_limits(self, request, object_list):
    if request and hasattr(request, 'user'):
        if request.user.is_authenticated():
            object_list = object_list.filter(user=request.user)
            return object_list

    return object_list.none()

Alternately/additionally, you can make resources that only return the user’s objects by overriding the ModelResource.apply_authorization_limits method and automatically associate the user with created objects by overriding the obj_create method, something like:

class PerUserModelResource(ModelResource):

  def obj_create(self, bundle, request=None, **kwargs):
    return ModelResource.obj_create(self, bundle, request, user=request.user)

  def apply_authorization_limits(self, request, object_list):
    return object_list.filter(user=request.user)

Then, you can inherit from the PerUserModelResource and/or make PerUserAuthorization the authorization for the resource.

class ImageGroupResource(PerUserModelResource):
  study = fields.ForeignKey(StudyResource, "study")
  uploads = fields.ToManyField('cm.api.UploadResource', 'uploads', null=True)

  class Meta:
    queryset = ImageGroup.objects.all()
    list_allowed_methods = ['get', 'post']
    detail_allowed_methods = ['get', 'post', 'put', 'delete']
    resource_name = 'cm/imagegroup'
    authorization = PerUserAuthorization()
    filtering = {
        'name': ALL,
        'created_dt': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'],
    }

Backbone and django-tastypie are nicely documented. Take the time to build a simple proof of concept and read through the docs a few times. They go together like peas and carrots.

Leave a comment