the red penguin
HOME ABOUT SITEMAP BLOG LOGIN

6. Django templates

We can edit the view we just created so that it uses a template. Note we commented out the html created previously and have added the template below it.

def simple_view(request):
    addresses = Address.object.all()
    first_address = address[0]
    resident_name = str(first_address.resident)
    # html = "Name: "+resident_name+"Address:"+
        first_address.street_name+""
    return render(request, 'helloworld/simple.html', {'address':first_address, 'name': resident_name})

We’re using a template called simple.html.  We haven’t created this yet.

By convention the Django app will keep the templates in a directory called templates – this can be changed in the settings.

We’ve previously created the helloworld subdirectory in templates so we just need to go here and add a file called simple.html.

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>Simple Title For This Page</h1>
        <p>
            Name: {{ name }}<br />
            Address: {{ address }}
        </p>
    </body>
</html>

We can use code instead of variable names, eg

Name: {% name.upper() %}

We can also do this:

templates/helloworld/base.html

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="HTML,Django,Tutorial">
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

templates/helloworld/simple.py

{% extends 'base.html' %}
{% block content %}
<h1>Simple Title For This Page</h1>
<p>
Name: {{ name }}<br />
Address: {{ address }}
</p>
{% endblock %}
Wednesday 20 October 2021, 568 views


Leave a Reply

Your email address will not be published. Required fields are marked *