014-Django Prepare Template

Objectives: Django Prepare Template

Django Prepare Template

Django Prepare Template

1. Create a Template

Create all_members.html inside the templates folder:

<!DOCTYPE html>
<html>
<body>

<h1>Members</h1>

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }} {{ x.lastname }}</li>
  {% endfor %}
</ul>

</body>
</html>

Tip:

The {% %} brackets are Django template tags that allow you to add logic inside HTML. Here, it loops through all members.

2. Modify the View

Update your views.py to send the model data to the template:

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

def members(request):
  mymembers = Member.objects.all().values()
  template = loader.get_template('all_members.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))

Example:

This view collects all members, loads the template, sends the data, and renders the HTML in the browser.

3. Start the Server

Run the server in your project folder:

python manage.py runserver

In your browser, open:

127.0.0.1:8000/members/

You should see a list of all members from the database displayed in a web page.

Advice:

Always make sure your template filename and view references match. Any typo will cause Django to fail loading the page.

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::