Blog

Django Template extending

Posted on in 

In this tutorial I will describe how you can extend from Django’s templates, and create your own.

  1. Create a templates folder in the root of your site.

2 visit the website. Create a static folder in the root of your site.

  1. Enable the templates folder in your root settings.py file:
1
2
3
4
5
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
  1. Make sure django.contrib.staticfiles is an installed app:
1
2
3
4
5
6
7
8
9
10
11
12
13
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
  1. Create the following files:
  • mysite/templates/base.html
  • mysite/templates/mysite/home/home.html
  • mysite/static/mysite/style.css
  1. Use the following base.html:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {% load staticfiles %}
    <html>
    <head>
    <title>MySite</title>
    <link rel="stylesheet" href="{% static ""mysite/css/site.css"" %}">
    </head>
    <body>
    {% block content %}
    {% endblock %}
    </body>
    </html>
  2. Use the following home/home.html

1
2
3
4
5
6
7
{% extends "base.html" %}
{% block title %}MySite{% endblock %}
{% block content %}

MY HOMEPAGE HERE

{% endblock %}
  1. Configure the urls.py to makes sure you will be routed to the homepage:
1
2
3
4
5
6
7
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', 'mysite.views.home', name='home'),
..
  1. Create the following file:
    mysite/views.py
1
2
3
4
5
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

def home(request):
return render_to_response('home/home.html')

Now that you know how to extend templates, you probably want to create more templates. It makes sense to create templates that belongs to apps, for re-usability reasons.

Comments