Hi, guys. Now we want to add the template into django. And now, we are using bootstrap for templating. The template that we want to use is default by bootstrap, using Blog Template Example.

Static 

First of all, we create the static directory on the root, and put the bootstrap files on there. All file static, likes an image, an icon, css file, etc. will be located under static directory.

And then create directory called templates, and put the index.html on this directory. All of html file will be under templates directory.

So we will got the structure like this :

static directory structure

Setting 

Now, we make a setting the source code so that we can load the template and also static files 

Open the settings.py file. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os
location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', x)
 
...
 
STATIC_URL = '/static/'
 
STATICFILES_DIRS = (
    location('static'),
) 
 
TEMPLATE_DIRS = (
    location('templates'),
)

 

location variable is needed to get real path, so we just call location('static') instead of using manualy "/home/html/project/static"

Also we should make change the index.html, so that we can load static url to load the css files and javascript files. We don't need to make many changes, just add the static url to get the static files. For example, 

1
2
3
...
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
...

 

make it into like this one

1
2
3
...
<link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet">
...

 

Please make change to all script that need to load the static files. If all html script have been changed, now we make script in view and url to test the template. Make views.py inside of project directory (parallel with settings.py and urls.py), and add this script to views.py

1
2
3
4
5
from django.shortcuts import render_to_response
from django.template import RequestContext
 
def home(request):
    return render_to_response('index.html', {}, context_instance=RequestContext(request))

 

Also this is for urls.py 

1
2
3
4
urlpatterns = patterns('',
    url(r'^$', 'myblog.views.home', name='home'),
    ...
)

 

Okay, now try to run the service and open from browser http://localhost:8000/.

bootstrap template

Okay, we have load the template in django.

Next?

Next, we try to using MVC pattern in django (it called MVT). So we get the data from models in views and show it into template

Thanks    

Comments

Add comment

authimage