Basic Django templates
Instead of using Python to create all the HTML, Django can load and render templates
- In settings.py specify the location of the templates, e.g.
TEMPLATE_DIRS = [
os.path.join(BASE_DIR, ‘templates’),
] - Create the folder within the projects folder,
i.e. <dev root>/Projects/DjangoTest/templates - In the ../templates folder, create a new file, say testtemplate.html, and create a very basic html page, e.g.
<html>
<body>
<p>Test template</p>
</body>
</html> - Create a view to test the template, in the views.py
from django.template.loader import get_template
from django.template import Contextdef templateDemo(request):
template = get_template(‘testtemplate.html’)
html = template.render(Context({}))
return HttpResponse(html) - Set up the url, in the urls.py:
url(r’^templatedemo/’, templateDemo), - In the same file, import the view
from DjangoTest.views import templateDemo - Test it out – point your browser to http://localhost:8000/templatedemo/
You should see a page with “Test template” and nothing else - Now we’ll put some variable data in.
- In the template file (testtemplate.html), add the following line:
<p>And the answer is: {{answer}}</p> - Change views.py, line to:
html = template.render(Context({‘answer’: 25})) - Refresh the browser window. You should now see:
Test template
And the answer is: 25
- In the template file (testtemplate.html), add the following line: