Django Template extending

Posted on in Django Python

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.

3. Enable the templates folder in your root ** file:

            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],

4. Make sure *django.contrib.staticfiles* is an installed app:

    STATIC_URL = '/static/'
        os.path.join(BASE_DIR, "static")

5. Create the following files:


6. Use the following *base.html*:

        {% load staticfiles %}
                <link rel="stylesheet" href="{% static ""mysite/css/site.css"" %}">
                {% block content %}
                {% endblock %}

7. Use the following *home/home.html*

        {% extends "base.html" %}
        {% block title %}MySite{% endblock %}
        {% block content %}
        {% endblock %}

8. Configure the ** to makes sure you will be routed to the homepage:

    from django.conf.urls import url
    from django.contrib import admin
    urlpatterns = [
        url(r'^$', 'mysite.views.home', name='home'),

9. Create the following file:

        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.

Post a Comment

Your email is never published nor shared.
Required fields are marked *