009-Django Templates

Objectives: Django Templates

Django Templates

Django Templates

1. Creating a Template

Create a templates folder inside your app (members) and create a HTML file named myfirst.html. The structure should be:

my_tennis_club/
  manage.py
  my_tennis_club/
  members/
    templates/
      myfirst.html

Open myfirst.html and insert:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>

</body>
</html>

Real-life Example:

The template is like the blueprint of a webpage — it defines how content will look when sent to the user’s browser.

2. Modifying the View

Update your views.py to use the template:

from django.http import HttpResponse
from django.template import loader

def members(request):
    template = loader.get_template('myfirst.html')
    return HttpResponse(template.render())

Advice:

Templates keep the HTML separate from Python logic. This makes your code cleaner and easier to maintain.

3. Adding the App to Settings

Tell Django about your new app in settings.py by adding it to INSTALLED_APPS:

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'members',
]

Then run migrations:

python manage.py migrate

Real-life Example:

Adding your app to settings is like registering a new department in a company. Django needs to know it exists before using it.

4. Running the Server

Start the server:

python manage.py runserver

Open http://127.0.0.1:8000/members/ in your browser to see the template output.

Real-life Example:

Think of this as turning on the lights in your webpage. Now your HTML blueprint (template) can be seen in action by the user.

Advice:

Always check the browser output after creating templates. Small mistakes in HTML or template tags can prevent the page from rendering correctly.

Exercise:

Create another template called about.html and modify the view to display it at /about/. What changes are needed in urls.py and views.py?

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::