rest2backbone

rest2backbone can help to quickly build a web browser interface for RESTful API in Django.  It’s achieved by connecting two notable components Django REST Framework on server side and Backbone.js on client side.   Django REST Framework enables us to quickly define RESTful API from existing Django models, we just need to create few classes in a similar way, how Django forms classes are defined.  Backbone.js is a MVC framework that can consume server RESTful API and provide us with Models and Collections in Javascript.  Also bring additional level of order into client JS code, forcing us to put data into models,   use views and templates, and providing a controller/router for single page applications.

However to use these two together we have to duplicate a significant amount of code between definitions of models in Python and definitions of models in Javascript.  Also for models we have to create  forms to display and update models, validate forms for correct values etc.  rest2backbone tries to minimize this duplication and generate as much JS and HTML code  as it can – so we can focus on client logic mostly.

Features

rest2backbone can generate for you:

  • models, collections and index for all resources available via API (  index is a 2 columns collection with id and string representation of the model –  useful  for dynamic selects, auto-completes etc.
  • support for  validation of models (as per definitions of models in Django –  types, limits, formats …), filtering, ordering and pagination of collections.
  • form templates for given models, including some code to save form data into model and display validation errors on the form.
  • some extensions to Django REST Framework – like HTML 5 input types, viewset with indexes, …
  • Dynamic widgets –   contains small framework for dynamic widgets to be used in in form templates – includes dynamic select (refreshes from models index) and in place edit (edits related model in place – in parent form).
  • it uses Django internationalization framework – so no problem to use in several languages

rest2backbone is now rather small (I’d say a proof of concept),   but I hope it may grow as I’ll use it in my other projects and maybe somebody else will find it useful and will contribute.

Quick Start

You can quickly build a modern one page web application in few steps:

  1. Create your models in Django, if necessary add additional logic to them etc.
  2. Create a RESTFul API – as described in Django REST Framework documentation    – I prefer to put these definitions in resources.py module.    We provide modified ModelSerializer and ViewSetWithIndex in rest2backbone.resources  – so use these  (see sample_app/resources.py) .
  3. Link API ViewSets to urls via modified router :
    from rest2backbone.resources import IndexedRouter
    router=IndexedRouter(trailing_slash=False)

    This is our modified router, which can also provide indexes.   It’s very important that it’s initialized with trailing_slash=False because Backbone is expecting it.
    Then register any model ViewSets created earlier with register function, and finally link router’s  urls to urlspatterns :

    # add to  urlpatterns  list
    url(r'^api/', include(router.urls)),
    #needed by rest_framework for browsable API
    url(r'^api-auth/', include('rest_framework.urls',
                                   namespace='rest_framework')),
  4. Add also an url for generated  javascript models ( it uses router to generate JS models for all registered ViewSets):
    from rest2backbone.views import restApi
    
    #add to urlpatterns list
    url(r'^js-restAPI/?$', restApi.as_view(), {'router': router, 'url_prefix':'/api'}, name='rest-api'),

    In Javascript code models are availabe under global object restAPI –   restAPI.YourModelName and restAPI.YourModelNameList – for collection and restAPI.YourModelNameIndex – for index

  5. Create  HTML template page for your application,   it should contain following script references  in the header:
    <script src="{{STATIC_URL}}js/jquery-2.0.2.js"></script>
    <script  src="{% url 'django.views.i18n.javascript_catalog'  packages='rest2backbone'%}"></script>
    <script  src="{{STATIC_URL}}js/underscore-min.js"></script>
    <script  src="{{STATIC_URL}}js/backbone-min.js"></script>
    <script src="{% url 'rest-api' %}"></script>
    <script  src="{{STATIC_URL}}js/api-forms.js"></script>

    Note Django localization JS library  – it’s needed to provide global gettext function, which localizes strings in JS – mostly validation errors.
    And also put somewhere in the body this :

    <!-- Templates generated by rest2backbone -->
    {{params.forms.render_all}}

    It generates  form templates for registered models.
    You also have to link your application template to urlpatterns:

    from rest2backbone.forms import FormFactory
    
    #add to urlpatterns list
    url(r'^/?$', TemplateView.as_view(template_name='sample/app.html'), {'forms': FormFactory(router)}),

    This will generate form templates for all registered models – the form template has id  attribute  r2b_template_yourmodelname or   r2b_template_yourmodelname_ro (for read only template).

  6. Now you can start to write some code for your client application using Backbone.js (this tutorial and this tutorial  are nice to get basic overview of Backbone.js) – all  generated models, collections, indexes are available  in restAPI global object.  So you can create some views  for these models and collections- rest2backbone provides  another JS API to help with views in formsAPI global object – it contains several base objects, which you can extend – formsAPI.BaseView (generic view that renders template against model attributes), formsAPI.FormView (with some functions to support form saving and validation) and formsAPI.BaseListView (base for views of collections – supports pagination).  Your views can leverage generated templates – especially for displaying forms.
    You can take a look at sample application code  – app.html   and app.js contain all code for the client side.

Install,   Develop

rest2backbone in hosted on github here. Looks at readme –   how to install and get sample application running – that should be app. 5 minutes task.

If you would like to extend, modify you can fork it on GitHub,   any contribution is welcomed indeed.

Where is API documentation?  Sorry, not yet –   I’ll try – for now just look into code –   it’s still small.   Key elements are mentioned above in Quick Start.

My Digital Bits And Pieces