Writing all the required html files in the templates folder

  • As we already created a templates folder in the previous program, let's add these html files to it which uses inheritance concept.
  • Create a layout.html file and add below code to it.
<!DOCTYPE html>
<html>
    <head>
        <title>template-inheritance</title>
        <style>
            li {
                display: inline; <!--to display the navbar horizontally-->
            } 
            footer{
                text-align: center;
            }
        </style>
    </head>
    <body>
        <header>
            <ul>
                <li><a href="/home/">Home</a></li>
                <li><a href="/contact/">Contact</a></li>
                <li><a href="/about/">About</a></li>
              </ul>
        </header>
            <hr>  <!-- for horizontal line-->
        <main>
            {% block content %}
            {% endblock content%}
        </main>
            <hr> 
        <footer>&copy; 2024 Copyright: All rights reserved. your_domain_name.com.  </footer>
    </body>
</html>
        
  • create a home.html file and add the below contents.

{% extends "layout.html" %}

{% block title %}Home{% endblock %}

{% block content %}
    <h1>Home page</h1>
    <p>{% lorem 1 %}</p>
{% endblock content%}
        
  • create about.html file and below contents.

{% extends "layout.html" %}

{% block title %}about{% endblock %}

{% block content %}
    <h1>About page</h1>
    <p>{% lorem 1 %}</p>
{% endblock content%}
        
  • create contact.html file and add below contents.

{% extends "layout.html" %}

{% block title %}contact{% endblock %}

{% block content %}
    <h1>Contact page</h1>
    <p>{% lorem 1 %}</p>
{% endblock content%}
        

Writing view.py file to render the above html file and setting urls.

  • make changes in urls.py file as show below.

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home,name="home"),
    path('home/',views.home,name="home"),
    path('contact/',views.contact,name="contact"),
    path('about/',views.about,name="about"),
]
        
  • make these changes in view.py

from django.shortcuts import HttpResponse,render
from datetime import datetime,timedelta

def home(request):
    return render(request,"home.html") 

def contact(request):
    return render(request,"contact.html") 

def about(request):
    return render(request,"about.html") 
        
  • Run local server python manage.py runserver and redirect url's as specified in the urls.py file and see the output.

Watch a quick video summary on how to run this program

Watch it at 2x speed