Friday 10 June 2016

Working with views and templates with Django

This tutorial serves as a quick guide (my notes) on how to utilize templates with your views in Django.

Lets first deploy a new instance of Django:

pip install Django==1.9.7

mkdir C:%HOMEPATH%\Desktop\django
cd C:%HOMEPATH%\Desktop\django

django-admin startproject myapp

and then create our new web app:

cd myapp
python startapp nagios

python migrate
python runserver

And ensure the website comes up OK.

Now lets make a start on creating out template object - this will be done interactively via the shell initially:

python shell

from django import template
import datetime
myTemplateObject = template.Template('<html><body>The current time is {{ thetime }}.</body></html>')
myContextObject = template.Context({'thetime':})

The above will simply output the date and time. In other languages this is very similar to anchors which allow you insert specific data into a specific point in a document.

Now - a slightly more complex example might be where we wish to insert a number of rows into an HTML table - we can utilize other python types like lists as well - for example:

from django import template

resultString = ''

tableelements = template.Template('<td> {{ element }} </td>')
for element in ('Harry', 'John', 'Ben'):
    resultString += tableelements.render(template.Context({'element': element}))

myTemplateObject = template.Template('<html><body><table style="width:100%"><tr> {{ resultString }} </tr></table></body></html>')
myContextObject = template.Context({'resultString': resultString})

Now we will apply this to a view, for example in our file:

Create a the folder 'mymonitor' and the file (template) template.html and ensure that you add the anchor in: {{ element }}

and then add the following to your file:

def table1(request):
    return render(request, 'mymonitor/template.html', {'element': resultString})


Post a Comment