Receive our weekly advanced programming tips for FREE
04.May
Create a template in django
0
| 0 votes
Autor: bookkeeper
Chapter: Django
Every view renders a webpage. For this Django has a own template system.

1. First we create a templates folder in our root project and change into it

2. Now create a folder what ever you like, the best would be the name of the application, like homepage and change into it

3. When create a index.html, to make clear that is the entry point of this application template

4. Create your our html template or for example:


<html>
<head>
    <title>My Blog Index</title>
</head>
<body>
    <h3>Index Page</h3>
</body>
</html>


5. Open the global settings

6. Import on the top the os module and modify the TEMPLATE_DIRS variable and add the path, for example

import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
#....
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( os.path.dirname(__file__), 'templates' ),
)
#....

7. Open the views.py file

8. Import the render_to_response function. This will do the job for you, parse a template and return a valid HttpResponse object.

9. Use the render_to_response in the view, for example

from django.shortcuts import render_to_response
def index(request):
    return render_to_response('homepage/index.html')  

10. The first parameter is the template.

11. Start the dev server: python manage.py runserver



Wasn't that easy?!

The template engine is very powerfull more in future