Sunday, 3 August 2014

how create a django template


good software engineering is separate from UI and business logic

now we will try to implement template in django it nice mechanism where where your application design separate from business logic first create a folder in store folder

next open setting file and write bellow code:

import os.path
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)

this is a variable where i have set my django template path so django can access easily my template folder

next create a html file like:

<title>{{ head_title }}</title>
<h1>{{ page_title }}</h1>
<p>{{ page_body }}</p>

and save it home.html, {{anything}} this means it indicate a print a variable

now open your app folder and edit file and write bellow code

1. from django.http import HttpResponse
2. from django.template import Context
3. from django.template.loader import get_template
4. def main_page(request):
5. template = get_template('home.html')
6. variables = Context({
     'head_title': 'Django App',
     'page_title': 'Welcome to Django App',
     'page_body': 'This is test page'
7. output = template.render(variables)
8. return HttpResponse(output)

this is a views where we will calculate or process all data and send to template,
we will send a data array and all array element key is a veriable in template

now i will describe what actule work in what line

1-3. this line for load all require django module
5. load my template that i have created in template folder
6. create a data array
7. send data array to template and template will parse this array to variable
8. send a response to user

now you have got a nice cocktail glass