Category Archives: Templates

Basic Django templates

Instead of using Python to create all the HTML, Django can load and render templates

  1. In specify the location of the templates, e.g.
    os.path.join(BASE_DIR, ‘templates’),
  2. Create the folder within the projects folder,
    i.e. <dev root>/Projects/DjangoTest/templates
  3. In the ../templates folder, create a new file, say testtemplate.html, and create a very basic html page, e.g.
    <p>Test template</p>
  4. Create a view to test the template, in the
    from django.template.loader import get_template
    from django.template import Context

    def templateDemo(request):
    template = get_template(‘testtemplate.html’)
    html = template.render(Context({}))
    return HttpResponse(html)

  5. Set up the url, in the
    url(r’^templatedemo/’, templateDemo),
  6. In the same file, import the view
    from DjangoTest.views import templateDemo
  7. Test it out Рpoint your browser to http://localhost:8000/templatedemo/
    You should see a page with “Test template” and nothing else
  8. Now we’ll put some variable data in.
    1. In the template file (testtemplate.html), add the following line:
      <p>And the answer is: {{answer}}</p>
    2. Change, line to:
      html = template.render(Context({‘answer’: 25}))
    3. Refresh the browser window. You should now see:
      Test template
      And the answer is: 25