Setting up Backbone Application with Django - Server (Part 2)
Published: July 24, 2012, 1:18 p.m. #webdev #backbonejs #Django
In this part we will focus on our serverside of simple application we've created in part 1. I want the server API to communicate in JSON. In this tutorial we will create one simple GET response for retrieving a list of our objects stored in database. Also we will enable default admin for our project to be able to edit items easily.
Last time we ended with this structure:
1. Creating models
edit your mytest/models.py and enter this code in the file:
from django.db import models
class Item(models.Model):
"""Category model."""
title = models.CharField( max_length=100, )
def __unicode__(self):
return u'%s' % self.title
our model will have name Item. the __unicode__ method is there for representation of this object by it's title. This is usefull for Django Admin or shell. When working with instances of model, they will carry the title as a description if you type print(item), where item is instance of our model Item.
2. Enabling Django Administration
Belieave most of you know how to do this, but still I'll put it down here.
First we have to synchronize our database.
- Go to mysite/settings.py and find INSTALLED_APPS and uncomment the line 'django.contrib.admin'
- From your console run command:
manage.py syncdb
Now we will enable the administration. Create a new file mytest/admin.py and enter this code:
from django.contrib import admin
from mytest.models import *
class ItemAdmin(admin.ModelAdmin):
pass
admin.site.register(Item,ItemAdmin)
I like to register models this way right ahead, because in 99% of cases I need to do some adjustments to admin page for models.
Finally go to mysite/urls.py and uncomment those 3 lines for admin. This is how the file should look like:
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# some previous stuff here
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^test', 'myapp.views.test'),
)
In your browser type admin url http://localhost:8000/admin/ and after login you should see the line for our Items we've just created:
Add a few items in your administration to have some data to work with.
3. Create URL to API view
This will be simple - our new view, let's call it "data" will be available at url /api/data. Edit your mysite/urls.py and add a new linet to urlpatterns:
url(r'^api/data', 'myapp.views.data'),
To test it out we need still our view...
4. Working with JSON
There are two options how to create json objects, we will discuss both here:
4.1 Django serializer
Let's run our shell (type: manage.py shell) and try out Django serializer
>>> from django.core import serializers
>>> from myapp.models import Item
>>> # as first param pass format, second are models
>>> data = serializers.serialize("json", Item.objects.all())
>>> data
'[{"pk": 1, "model": "myapp.item", "fields" : {"id": 1, "title": "pivo"}},
{"pk": 2, "model": "myapp.item", "fields" : {"id": 2, "title": "beer"}}]'
Hm... This is not exactly the format I'm expecting for my model in resposne. I want to make this example easy (to avoid overriding classes). Let's have a look at simplejson now
4.2 SimpleJSON
SimpleJSON is available as standalone python package and currently is part of Django Framework (1.4.0) or you can download it using pip by typing:
pip install simplejson
Let's run our shell (type: manage.py shell) and try out simplejson
>>> from django.utils import simplejson as json
>>> # otherwise use:
>>> # import simplejson as json
>>> #
>>> # create our object here
>>> a = { 'id': 1, 'name': 'Wolverine' }
>>> json.dumps(a)
'{"id":1, "name": "Wolverine"}'
>>>
As you can see this example is simple to use simplejson. Maybe that's the reason why it's called "simple"-json :D.
5. Creating API view
Let's open myapp/views.py again and add these two lines at start:
from myapp.models import Item
from django.utils import simplejson as json
and a new method:
def data(request):
mimetype = 'application/json'
udata = Item.objects.all()
sdata = []
for d in udata:
a = {'id': d.id, 'title': d.title }
sdata.append(a)
return HttpResponse(json.dumps(sdata), mimetype)
Explanation:
First we need to fetch our data, so we use Item.objects.all(). These objects are stored to variable udata, where u stands for unsafe (hungarian notation). Because I don't want to use serializer I have to create the dictionary i want to send out as response. This is stored into sdata (s stands for safe).
As most of views in Django, even this will return HttpResponse object. Here we use our simplejson encoder as well as we set the mimetype of our response.
NOTE: Of course I would like to write at least some transformation method to my models, to keep the data methods with my models, but this is just an example how to create a response. If you are interested in a way how to create RESTful API with Django, I'm currently testing a way how to create this API views as easy as possible. After some research I'll put some tutorial on this blog too.
If you now try out http://localhost:8000/api/data in your browser, you should see simple response, depending on your data u entered. Here is mine:
Yes, I do have installed addon JSONView 0.0.30 in my Chrome browser .
Summary
In this part we've explored possibilities of creating simple json response, set up admin page for our demo and created API view. The view is just a list of items in our table. More complicated stuff comming soon :). If you have any questions, leave me a comment I'll be glad to answer them for you. Thanks for reading!