Skip to content

Instantly share code, notes, and snippets.

@victorespigares
Created January 6, 2012 01:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorespigares/1568294 to your computer and use it in GitHub Desktop.
Save victorespigares/1568294 to your computer and use it in GitHub Desktop.
This snippet shows how to bootstrap your Backbone models with Tastypie. If you're using 'api_name' for the URL of your api, make sure you add it to the Resource meta, otherwise 'resource_uri' will be empty when accessing from the view, but not from api ur
class CourseResource(ModelResource):
class Meta:
queryset = Course.objects.all()
resource_name = 'courses'
# without this resource_uri is empty in the view!
api_name = settings.API_VERSION
# API Tastypie
from tastypie.api import Api
v1_api = Api(api_name = settings.API_VERSION) #settings.API_VERSION = 'v1'
v1_api.register(CourseResource())
v1_api.register(LessonResource())
urlpatterns = patterns('',
url(r'^api/', include(v1_api.urls)),
)
def dashboard(request, nav):
# Empty forms for the backbone templates
courseForm = CourseForm(auto_id='%s', label_suffix='')
lessonForm = LessonForm(auto_id='%s', label_suffix='')
# All courses for current user
apiCourse = CourseResource()
# like http://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views
# but for a list of objs
courses = apiCourse.obj_get_list()
bundles = (apiCourse.build_bundle(request=request, obj=course) for course in courses)
dehydrated = [apiCourse.full_dehydrate(bundle) for bundle in bundles]
return render_to_response('teachers/dashboard.html', {
'courses_json': apiCourse.serialize(None, {'objects': dehydrated}, 'application/json'),
'courseForm': courseForm,
'lessonForm': lessonForm,
'nav': nav,
}, context_instance=RequestContext(request))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment