Creating a base template

Setting up templates in Django is an essential part of building dynamic web applications. Templates allow you to define the structure of your HTML pages and dynamically populate them with data from your Django views. Here’s a step-by-step guide on how to set up and use templates in Django:

1. Create a Django Project

First, if you haven’t already created a Django project, you can do so by running the following command in your terminal:

django-admin startproject myproject
cd myproject

2. Create a Django App

Within your project, create an app where you will define your views, models, and templates:

python manage.py startapp myapp

3. Set Up Template Directory Structure

Django looks for templates in specific directories. Typically, you’ll create a templates directory within your app or in your project’s root directory. You can organize your templates as follows:

  • Global templates: Create a templates directory at the root of your project.
  • App-specific templates: Create a templates directory inside your app directory.

Example Structure:

myproject/
    myapp/
        templates/
            myapp/
                example.html
    templates/
        base.html
    myproject/
        settings.py

4. Configure Template Settings

In your project’s settings.py file, you need to inform Django where to look for templates. Modify the TEMPLATES setting like this:

# myproject/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],  # Add this line to include the global templates directory
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

  • DIRS: This is a list of directories where Django will look for templates. Adding BASE_DIR / 'templates' allows you to use a global templates directory.
  • APP_DIRS: If set to True, Django will look for a templates directory within each app.

5. Create a Base Template

It’s common to create a base template that other templates can extend. This reduces redundancy in your HTML files.

<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Site{% endblock %}</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
    <header>
        <h1>Welcome to My Site</h1>
    </header>

    <nav>
        <!-- Navigation links -->
    </nav>

    <main>
        {% block content %}
        {% endblock %}
    </main>

    <footer>
        <p>&copy; 2024 My Site</p>
    </footer>
</body>
</html>

6. Create and Extend a Template

You can now create specific templates for your app by extending the base template:

<!-- myapp/templates/myapp/example.html -->
{% extends 'base.html' %}

{% block title %}
Example Page
{% endblock %}

{% block content %}
<h2>This is the Example Page</h2>
<p>Welcome to the example page for our app!</p>
{% endblock %}

7. Create a View to Render the Template

In your app’s views.py, create a view that will render the template and pass data to it if needed:

# myapp/views.py
from django.shortcuts import render

def example_view(request):
    context = {
        'message': 'Hello, this is a message from the view!',
    }
    return render(request, 'myapp/example.html', context)

8. Map the View to a URL

In your app’s urls.py, map the view to a URL:

# myapp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('example/', views.example_view, name='example'),
]

Finally, include your app’s URLs in the project’s main urls.py:

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]

9. Test the Setup

Run your Django development server:

python manage.py runserver

Navigate to http://127.0.0.1:8000/myapp/example/ in your browser. You should see the rendered template with the content you defined in example.html.

10. Static Files and Template Inheritance

If your templates rely on static files (like CSS, JavaScript, or images), make sure to configure Django’s static files settings. Typically, you’d place static files in an app’s static directory or in a global static directory in your project.

In your settings.py:

STATIC_URL = '/static/'

In your HTML templates, you can load static files using the {% static %} template tag:

<link rel="stylesheet" href="{% static 'css/style.css' %}">

Conclusion

By following these steps, you can set up and efficiently manage templates in a Django project. Templates provide a powerful way to create dynamic, reusable, and maintainable HTML in your web application.