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

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

django-admin startproject myapp

and then create our new web app:

cd myapp
python manage.py startapp nagios

python manage.py migrate
python manage.py runserver

http://127.0.0.1:8000/

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 manage.py shell

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

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})
print(myTemplateObject.render(myContextObject))

Now we will apply this to a view, for example in our views.py 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 views.py file:

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

0 comments:

Post a Comment