This allows you to build a consistent site layout and ensures that you don't have to repeat the same code in multiple templates.
To create a template in Django, you will need to create a template directory in your Django app and put your templates inside it. Django will automatically find and use templates in this directory when you use the render() function in your views.
To create a base template, you can use the extends tag to specify the parent template that your template will inherit from. For example, you might create a base template called base.html that looks something like this:
<!DOCTYPE html>
<html>
<head>
{% block head %}
<title>My Site</title>
{% endblock %}
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
This template defines two blocks: head and content. Child templates can override these blocks by using the block tag. For example, you might create a child template called home.html that looks like this:
{% extends "base.html" %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block content %}
<h1>Welcome to my site!</h1>
<p>Here's some content.</p>
{% endblock %}
To include this template in your Django view, you would use the render() function and pass it the request object and the name of the template you want to use. For example:
from django.shortcuts import render
def home(request):
return render(request, "home.html")
When Django renders this view, it will find the home.html template and use it to render the response. The home.html template will inherit from the base.html template and override the head and content blocks to create the final HTML that is sent to the client.
I hope this helps! Let me know if you have any questions.