Django Starter 6 — Main Index

Rubaiyat Rahim
2 min readMay 26, 2024

--

Creating the main index page of the site.

Other parts of this series: Part 1 | Part 2 | Part 3 | Part 4 | Part 5

Create Main Template

  • Create the main template (myproject\players\templates\main.html) as follows:
{% extends "master.html" %}

{% block title %}
Chelsea Football Club
{% endblock %}


{% block content %}
<h1>Chelsea Football Club</h1>

<h3>Players</h3>

<p>Check out all the <a href="players/">Players</a></p>

{% endblock %}

Create Main View

  • Create the main view myproject\players\views.py in as follows:
from django.http import HttpResponse
from django.template import loader
from .models import Player

def players(request):
allplayers = Player.objects.all().values()
template = loader.get_template('all_players.html')
context = {
'allplayers': allplayers,
}
return HttpResponse(template.render(context, request))

def details(request, id):
theplayer = Player.objects.get(id=id)
template = loader.get_template('details.html')
context = {
'theplayer': theplayer,
}
return HttpResponse(template.render(context, request))

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

Add URL

  • Add URL by putting the entry path(‘’, views.main, name=’main’) in the urlpatterns in myproject\players\urls.py as follows:
from django.urls import path
from . import views

urlpatterns = [
path('', views.main, name='main'),
path('players/', views.players, name='players'),
path('players/details/<int:id>', views.details, name='details'),

]

Add Link back to Main Index

  • Add a link (<a href=”/”>HOME</a>) back to the main index page in the list of Players page (myproject\players\templates\all_players.html) as follows:
{% extends "master.html" %}

{% block title %}
Chelsea Football Club - List of all Players
{% endblock %}


{% block content %}

<p><a href="/">HOME</a></p>

<h1>Players</h1>

<ul>
{% for x in allplayers %}
<li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li>
{% endfor %}
</ul>
{% endblock %}
  • The list of players page now has a link back to the main index page of the site as follows:
Fig: List of Players with a link back to the main index page of the site.

The Index Page

  • Finally the main index page of the site looks like as follows:
Fig: The main index page of the site.

--

--