Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Templates in Django: Part 3

DZone's Guide to

Using Templates in Django: Part 3

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

In a previous part of this tutorial series, we showed how you can create a simple web application using Django: How to develop a basic and very first website using Django.

In this post we are going to see how we can use Templates in Django to render HTML code on a web page. Initially we hard-coded the HTML part in views (views.py).

Let's start with a very basic idea of how templates work. Goto the directory you created in the previous part (or any other Django project) and run python manage.py shell (It is necessary that you open terminal using this command.)

Run the following commands:

What we have done is,
  1. Imported template module.
  2. Created a template using the Template() method. Everything inside the '{{}}' are variables. In our example we have two variables: name and age.
  3. To assign a value to this variable, we usedthe  Context() method, which takes python dictionary as argument.
  4. Now we render the template using render() method. It takes template.Context as argument and return Unicode String. You can render Template with various Context.

Now to use this in the project. You can write the following code in your views.py.

views.py
from django.http import HttpResponse
from django.template import Template, Context

def first_project(request):
    return HttpResponse("<h3>Welcome to my First Project</h3>")

def hello(request):
    list_books = ['one','two','three']
    html = """
 <html>
 <head><title>Homepage | Ronak khunt</title></head>
 <body>
  <h1>Welcome {{ uname }}</h1>
  <ol>
  {% for book in list_books %}
   <li>{{book}} ell</li>
  {% endfor %}
  </ol>
 </body></html> 
 """
    t = Template(html)
    c = Context({"uname":'Ronak','list_books':list_books})
    return HttpResponse(t.render(c))

Open your urls.py and set URL for this(hello()) method/View. Also note the use of the for loop. Using template does not solve the problem of hard-coded HTML.

To solve this problem Django provides get_template() method. Before using this method you have set TEMPLATE_DIRS in your settings.py. Open settings.py and add path to the directory in which you want to store your HTML files.

settings.py
......
......
#Don't forget trailing comma at the end.

TEMPLATE_DIRS = (
    '/home/user/django/first_project/templates',
)
......
......

Now createa  hello.html file in the template directory (you have to create this dir.) and write any code in it. In our case we will write the following code.

hello.html
<html>
 <head><title>Homepage | Ronak khunt</title></head>
 <body>
  <h1>Welcome {{ uname }}</h1>
  <ol>
  {% for book in list_books %}
   <li>{{book}} ell</li>
  {% endfor %}
  </ol>
 </body>
</html>

Now open the views.py file of your project and add following method.

views.py
#import get_template
from template.loader import get_template
#other import statement
...

def first_project(request):
    ...
def hello(request):
    ...

def hello2(request):
    t = get_template('hello.html')
    c = Context({"uname":'Ronak','list_books':list_books})
    html = t.render(c)
    return HttpResponse(html)

Open your urls.py and set the URL for this(hello2()) method/View.

Django also provides shortcut for this. You can use following method as shortcut.

views.py
#import render()
from django.shortcuts import render
#other import statement
...

def first_project(request):
    ...
def hello(request):
    ...
def hello2(request):
    ...

def hello3(request):
    return render(request, 'hello.html', 
                  {"uname":'Ronak','list_books':list_books})

We will also set the URL for this(hello3()) View. at the your urls.py will look someting like this.

urls.py
from django.conf.urls.defaults import patterns, include, url
from firstproject.views import first_project, hello, hello2, hello3

urlpatterns = patterns('',

    url(r'^first_project/

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Ronak Khunt. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}