Setting up Backbone Application with Django - Client (Part 1)
Published: July 24, 2012, 11:39 a.m. #webdev #backbonejs #Django
Today we will create a basic single page application using jQuery, Backbone on Django debug server. Even if we will run our code on local debug server, the code will be ready for switch to production, so don't worry about it now :). We will make it step by step from the scratch, so don't worry about complexity and let's get started ...
1. Create new project and application
Start console in your projects folder and type:
django-admin.py startproject mysite
cd mysite
django-admin.py startapp myapp
In your directory you should see something like this:
In your mysite/settings.py find INSTALLED_APPS tuple and add a new line with 'myapp' at the end:
INSTALLED_APPS = (
# some stuff here..
'myapp',
)
2. Setup your database
For this example I'll use mysql, so login to your mysql and run these commands:
create database `testapp` character set utf8 collate `utf8_unicode_ci`;
create user 'testapp'@'localhost' identified by 'test';
grant all privileges on testapp.* to 'testapp'@'localhost' with grant option;
flush privileges;
3. Setup your mysql connection to your project
In folder mysite edit settings.py and here is how you databases should look like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'testapp',
'USER': 'testapp',
'PASSWORD': 'test',
'HOST': '',
'PORT': '',
}
}
You can test your settings by typing manage.py dbshell and your mysql console should run without any problems
Client side
4. Creating simple view
In your myapp/views.py enter this code:
# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponse
def test(request):
return render_to_response('test.html', {},
context_instance=RequestContext(request))
If you try to run this code, you'll get exception of missing test.html template. In this template file will our application be running. I like to store basic site templates into root of the project directory, so let's create directory 'templates' in your project and put a file 'test.html' in that directory. Put this content into your test.html file:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}app.js"></script>
</head>
<body>
<p>ok</p>
<div id="app"></div>
</body>
</html>
However, by default this template won't be found by django. We need to add a few lines to our project settings into mysite/settings.py
On top of the file put these lines:
import os
DIRNAME = os.path.abspath(os.path.dirname(__file__))
Find your TEMPLATE_DIRS = () config and add a line inside so it looks like this:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates"
# or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(DIRNAME, '../templates'),
)
5. Enabling the view from url
Edit your mysite/urls.py and add a line defining your url path to view into your urlpatterns definition, so the file mysite/urls.py looks like this:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^test', 'myapp.views.test'),
)
When you run your project by typing manage.py runserver you should see no error. In your browser you should see at address http://localhost:8000/test this result:
When you show the source code you will see following:
As you can notice, we include jQuery library, Underscore.js and Backbone.js. Our template tag {{ STATIC URL }} has been replaced with /static/. However if you click the link "/static/app.js" you will get 404 error:
Let's fix that in the next step...
6. Configuring static files
I like to place my site related static files into project directory into dir static. In your project create directory static and edit file static/app.js. Enter some content in the file so you can see if it's actually working or not. When you refresh your browser at url http://localhost:8000/static/app.js you will see still the same 404 error. That's because your static files aren't cofigured yet.
Go to your mysite/settings.py file and edit your STATICFILES_DIRS = () to look like this:
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
# site-related static files
('', os.path.join(DIRNAME, '..','static')),
)
After refresh it your app.js file should be displayed.
Summary
This is our final directory listing of our project:
In this first part we have learned how to create simple Django project to server static files for single page application based on Backbone. If you have any questions you can leave me a comment. At the end of this part here are some notes you should already know:
- If you want to add static files (like css, js, images) add them to /static directory
- Refer to static files in your template with {{ STATIC_URL }} tag. This will work while we use RequestContext for our responses
- Place your Backbone application into static/app.js
- Edit your layout in /templates/test.html