Django Templates Directory Structure
Last Updated :
04 Nov, 2024
Django templates allow us to define the structure and layout of HTML pages. But to render the templates, Django needs to know where to locate and load them. In this article, we will explain the path that Django uses for locating and loading templates, how we can customize it, and the different ways Django finds templates during the rendering process.
Django’s Template Loading System
Django has a flexible and powerful method for finding and loading templates. When a view requires a template, Django searches through specific directories in a defined order, based on the settings of our project.
Where Django Looks for Templates
By default, Django looks for templates in several predefined locations:
1. App-specific templates
Django automatically looks for templates in a subdirectory named templates within each app's directory.
For example, if our app is called blog, we would place our templates under:
myproject/
blog/
templates/
blog/
our_template.html
Each app in our project can have its own templates folder. This allows us to keep app-specific templates separate from templates used across the entire project.
2. Project-level templates
Django also looks for templates in directories listed in the DIRS option of the TEMPLATES setting in settings.py.
myproject/
templates/
base.html
navbar.html
footer.html
Note: The search order matters. Django will use the first matching template it finds.
The TEMPLATES Setting in settings.py
The primary way to tell Django where to search for templates is through the TEMPLATES setting in our settings.py file. Django uses the TEMPLATES setting to define a list of directories it will search for templates.
customize TEMPLATES Settings in settings.py filesNote: We can give any name to the templates folder. But 'templates' is the standard to use.
Let's break down this configuration:
- BACKEND: Specifies the template engine Django uses, which by default is 'django.template.backends.django.DjangoTemplates'.
- DIRS: A list of directories where Django will search for templates. In this example, Django looks in the templates directory located at the base of the project.
- APP_DIRS: If set to True, Django will automatically look for a templates folder within each installed app.
Example Rendering a Template
Let's say we have a app called myapp in our Django Project.
In myapp/templates/myapp create a html file called hello.html and add the following code.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello, welcome to my Django app!</h1>
</body>
</html>
In the view, we can render this template like this.
myapp/views.py
Python
from django.shortcuts import render
def hello_view(request):
return render(request, 'myapp/hello.html')
In this case, Django will look for home.html:
- First in any directories listed in DIRS in the TEMPLATES setting.
- Then inside any app's templates directory if APP_DIRS is set to True.
Output:
Customizing 404.html and 500.html Error Pages
Django provides default templates for 404 (page not found) and 500 (server error) pages. However, We can customize these error pages by creating our own templates. Django looks.for 404.html or 500.html in the templates directory first before rendering the default pages.
To render our custom 404.html or 500.html, we need to place them the templates directory itself.
In, myproject/templates add 400.html and 500.html.
myproject/
templates/
404.html
500.html
HTML
<!-- 404.html -->
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you're looking for does not exist.</p>
</body>
</html>
HTML
<!-- 500.html -->
<!DOCTYPE html>
<html>
<head>
<title>Server Error</title>
</head>
<body>
<h1>500 - Internal Server Error</h1>
<p>We are experiencing issues on our end. Please try again later.</p>
</body>
</html>
Testing Custom 404 Error Page
To test the custom 404.html error page, follow these steps:
Step 1: Set DEBUG = False in settings.py
To trigger custom error pages, we need to set DEBUG = False. Otherwise, Django will show its default debug error pages.
DEBUG = False
Step 2: Set ALLOWED_HOSTS
Since DEBUG = False, we also need to set ALLOWED_HOSTS in settings.py to allow the localhost or our IP.
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Step 3: Visit a Non-Existent URL
Go to our browser and visit a URL that does not exist, such as:
http://127.0.0.1:8000/some-nonexistent-page/
If everything is set up correctly, we should see our custom 404 page with the content of 404.html:
Testing Custom 500 Error Page
The 500 error page is triggered by server errors. Here’s how to test it:
Step 1: Set DEBUG = False in settings.py
This should already be done from the previous step:
DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Step 2: Trigger a Server Error Intentionally
To test the 500 error, we can manually raise an exception in one of our views.
For example, modify our hello_view in myapp/views.py to raise an error:
Python
from django.shortcuts import render
def hello_view(request):
# This will trigger a 500 error
raise Exception("This is a test server error!")
Output:
By following this article, we can easily work with Django Templates. We can follow the best practices to store and use these templates in our project.
Similar Reads
Explain the directory structure in Ember.js
Ember.js framework is designed to be used in large-scale, complex applications that require a robust and maintainable codebase. Ember.js uses the Model-View-Controller (MVC) design pattern, which separates an application into three main components: the model, which represents the data of the applica
6 min read
Linux Directory Structure
Prerequisite: Linux File Hierarchy Structure In Linux/Unix operating system everything is a file even directories are files, files are files, and devices like mouse, keyboard, printer, etc are also files. Here we are going to see the Directory Structure in Linux. Types of files in the Linux system.
5 min read
Handle and Iterate Nested Dictionaries in Django Templates
Django templates offer various tags and filters to work with data. they are designed to readable and expressive. To iterate through a dictionary which contains a dictionary itself as a Value we can use the " { % for % } " template tag to iterate over dictionary that contains dictionary. But Django t
4 min read
Ruby on Rails - Directory Structure
Ruby on Rails (often just called Rails) is a popular web application framework written in Ruby. It follows the convention over configuration principle, which means that it provides a lot of built-in conventions to simplify development. Understanding the Rails directory structure is key to effectivel
5 min read
Best Practice for Django Project Working Directory Structure
When organizing a Django project, the best practices regarding the structure of the working directory are followed to ensure that the project is maintainable, scalable, and supports collaboration. A well-constructed directory should not only keep your working base of code clean and logical but also
8 min read
Django Templates | Set - 1
There are two types of web pages - Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don't change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages
2 min read
extends - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
2 min read
Django settings file - step by step Explanation
Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 min read
Exploring Lazy Loading Techniques for Django Templates
In this article, we'll explore how to implement lazy loading in Django templates using JavaScript and HTML. If you have no idea about how to create projects in Django please refer to this Getting Started with Django. What is the Lazy Loading Technique?Lazy loading is a performance optimization techn
5 min read
How to create Custom Template Tags in Django ?
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed
4 min read