Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Django Template Inheritance – Avoid Redundant Code

  • Vinayak NishantVinayak Nishant
  • August 25, 2020
  • Django
Django Template Inheritance – Avoid Redundant Code

In this article, we will learn about a very important topic Django Template Inheritance. We’ve already learned what templates in Django are. We’ll carry our knowledge from there and build up on it.

What is Django Template Inheritance?

Template Inheritance is a method to add all the elements of an HTML file into another without copy-pasting the entire code. For example, consider the Facebook homepage.

Facebook
Facebook

Here the underlying theme of the web page; background, elements, etc., are same for all FB endpoints

There are two ways to achieve this:

  • Add the same CSS/JS/HTML code all the Endpoint Templates
  • Or, create a single file containing all common elements and then simply include it in others.

The second method is what exactly the Template Inheritance does.

Why Inheritance?

Just like Facebook, most of the Applications have long HTML codes for a single page itself. Now to write all that again and again for every page is not possible and a very inefficient method.

Thus Django provides the method of Template inheritance to ensure more efficiency and less repetition of code.

Another significant benefit with Template inheritance is that, if we modify the main file, it will automatically get changed at all places where it was inherited. Thus we don’t need to modify it at all other places

Hands-on with Django Template Inheritance

Let us create a base HTML file at the project level and then have the Django App templates inherit it.

1) Modify TEMPLATES in settings.py

To make the base file accessible, add the following line into TEMPLATES in settings.py as shown in screenshot below.

'DIRS': [os.path.join(BASE_DIR,'django_project/templates')],

This line executes the following function:

  • We get the path of the Django project directory using the predefined variable BASE_DIR (Our Django project folder)
  • Then with the os module, we join it to the django_project/templates file.

We are basically telling Django to search for templates outside the app, at the project level(path indicated by the above code) as well.

Basic Html
Base HTML path

2) Coding the Parent Base HTML file

Create a template BaseTemplate.html in the Templates folder present at the Django project directory level outside all the Apps.

And add the following code into the file:

<h2>Basic File Inheritence</h2>
{% block <block_name> %}
    <p> PlaceHolder to be Replaced</p>
{% endblock %} 

The base file should contain the {% block <block_name %} element.

When the base .html template will be inherited, the block content will be replaced by the other template’s contents.

3) Coding the App’s HTML Template files

Let us now code the App Template – “AppTemplate.HTML”, which will inherit the Base file. Add the code below into your template file in the Django App:

{% extends 'base.html' %}
{% block content %}
        <h3>Welcome to the App</h3><br>
{% endblock %}

Note: The {% extends ‘base.html’ %} line should always be present at the top of the file.

We need to add the template content in a similar Block with the same names as the parent file. The content of the blocks in the base file will be replaced with the corresponding block contents of this file.

4) Creating an App View to display the Template

We now just need a View to render and display our App Template. The Code for the View will be simply:

from django.shortcuts import render
def TemplateView(request):
    return render(request,'<app_name>/AppTemplate.html(path to the Template)')

The URL path for the view:

path('template/', TemplateView)

Implementing Template Inheritance

That’s all with the coding part, let us now implement the Templates in the browser.

Run the server and hit the URL

Template Inheritance
Template Inheritance

You can now continue to create pages with formatting that’s similar to the main template. In our case, that’s base.html.

If you add the required CSS, and HTML formatting options to base.html, the same styles will be applied to all templates that inherit the base file.

Conclusion

That’s it with the Template Inheritance!! See you in the next article!! Till then keep practicing !!

Vinayak Nishant
Vinayak Nishant
Articles: 60
Send Emails Using Django
Previous Post Send Emails Using Django
Next Post Tkinter Listbox and Option Menu - How to Use the Listbox and Option Menu Widgets?
Tkinter Listbox and Option Menu – How to Use the Listbox and Option Menu Widgets?

Related Posts

8 Common Django Commands That You Must Know

8 Common Django Commands That You Must Know

  • August 30, 2021
Deploy a Django App on Heroku – An Easy Step-by-Step Guide

Deploy a Django App on Heroku – An Easy Step-by-Step Guide

  • August 28, 2021
Hacker News Clone – Django Project Idea

Hacker News Clone – Django Project Idea

  • September 30, 2020

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.