015-Django Add Link to Details

Objectives: Django Add Link to Details

Django Add Link to Details

Django Add Link to Details

1. Create Details Template

Create details.html inside templates folder:

<!DOCTYPE html>
<html>
<body>

<h1>{{ mymember.firstname }} {{ mymember.lastname }}</h1>
<p>Phone: {{ mymember.phone }}</p>
<p>Member since: {{ mymember.joined_date }}</p>

<p>Back to <a href="/members">Members</a></p>
</body>
</html>

2. Make all_members.html Links Clickable

Update the template to link each member to their details page:

<!DOCTYPE html>
<html>
<body>

<h1>Members</h1>
<ul>
  {% for x in mymembers %}
    <li><a href="details/{{ x.id }}">{{ x.firstname }} {{ x.lastname }}</a></li>
  {% endfor %}
</ul>
</body>
</html>

Tip:

Using {{ x.id }} in the URL allows Django to know which member's details to display.

3. Create the Details View

Add a new view in views.py to handle the details page:

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

Example:

This view gets the member ID from the URL, fetches the corresponding record, and renders the details template.

4. Add URL Pattern

Update urls.py to include the details view:

from django.urls import path
from . import views

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

5. Start the Server

Run the server and check the results:

python manage.py runserver

In your browser, open 127.0.0.1:8000/members/ and click on a member's name to see the details page.

Advice:

  • Always include <int:id> in the URL pattern for detail pages.
  • Ensure that the links in all_members.html match the URL pattern.
  • If a member ID does not exist, Django will raise a DoesNotExist error — you can handle this later with try/except or get_object_or_404.

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