Friday, July 18, 2008

Django templates by examples

I've always had to learn this again and again. Finally here's the steps to finally do it. Here they are:

1. Make sure django can find that page. Modify the urls.py so that it would point to the function in the correct module. Here's a very short sample.

from django.conf.urls.defaults import *

urlpatterns = patterns('',
(r'^$','mylogin.myapp.views.main'),
(r'^report$','mylogin.myapp.reports.index'),
# Example:
# (r'^mylogin/', include('mylogin.foo.urls')),

# Uncomment this for admin:
# (r'^admin/', include('django.contrib.admin.urls')),
)

The comments are already there originally and I would like to say DO NOT BE FOOLED!!.. I spent quite a lot of time figuring out why on earth it would say that the module doesn't exist whilst I have clearly created it already. Answer is don't use the include. Just point to the function directly. Note the projectname.appname.module.function format.

2. Write the function. My example above points to 2 modules and here they are:

<views.py>
# Create your views here.

from django.template import Context, loader
from django.http import HttpResponse

def main(response):
t = loader.get_template('main.html')
c = Context({'username':'abdullah'})
return HttpResponse(t.render(c))

<reports.py>
from django.shortcuts import render_to_response

def index(request):
return render_to_response('report.html')


Note that in views.py I did the step to step of what it takes to display a template. In reports.py I used the django.shortcuts render_to_reponse function which takes a template file as the first variable and a dictionary to set the context as the optional second variable (and I didn't use it here).

3. Set the template location. You have to define it in the TEMPLATE_DIRS variable in your settings.py. Here's my sample:

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.
"/home/abdullah/python/mylogin/templates",
)


4. Create the directory you defined and put your templates in there. So here are my samples:

<mylogin/templates/main.html>
This is the new templated main {{username}}

<mylogin/tempaltes/report.html>
This is my report to you


Not much is it.. ;)

And that should be it.. You can now modify it and stuff.

0 comments: