Python - Django Templating and Includes

Getting Started

First, we gonna create our website using the Django Framework,. if you haven't done so, you may refer to my tutorial entitled Python Getting Started w/ Django Framework.

Creating and Installing our App

Next is we're gonna create and install a new app named aboutme. If you have no idea on how to create new app, please refer to my tutorial about Python - Django Creating New App.

Setting up our URLs

1. In your site directory, open urls.py and include our app in the urlpatterns by typing: index 2. In the app folder, open views.py. In my case, it will be on aboutme folder. Copy and save the ff:
  1. from django.shortcuts import render
  2.  
  3. def index(request):
  4. return render (request, 'aboutme/home.html')
3. In the app folder, create a new python file named urls.py with the ff codes:
  1. from django.conf.urls import url, include
  2. from . import views
  3.  
  4. urlpatterns = [
  5. url(r'^$', views.index, name='index'),
  6. ]

Creating our Templates Directory

1. We're creating a directory for our templates by creating a new folder in our aboutme app. This will organise all our templates into one directory. 2. Inside our templates folder, we're gonna create another folder named aboutme. Basically, django process all templates in a folder regardless of any apps and to avoid conflicts in the names of the templates, we create a new folder to group our templates.

Creating our HTML files

In the aboutme folder inside our templates folder, we create our html files. header.html
  1. <!DOCTYPE html>
  2. <title>Python - Django Templating</title>
  3. <meta charset="utf-8">
  4. </head>
  5. <div>
  6. {% block content %}
  7. {% endblock %}
  8. </div>
  9. </body>
  10. </html>
The {%%} is what we call the jinja logic home.html
  1. {% extends "aboutme/header.html" %}
  2.  
  3. {% block content %}
  4. <p>Hello World! Welcome to my Website</p>
  5.  
  6. {% include "aboutme/includes/footer.html" %}
  7. {% endblock %}
footer.html
  1. {% block content %}
  2. <p>This is our included footer</p>
  3. {% endblock %}
So basically, we have set up our views.py to direct to home.html. In our home.html, we have our header.html template which we have extends using {% extends "" %} and we have our include which we have included using {% include "" %}.

Running the Server

Run your server and it should look like this: templating That ends this tutorial. Happy Coding :)

Add new comment