Created
January 6, 2012 01:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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)), | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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