Connecting URLs, Views & Templates in Django

 Connecting URLs, Views & Templates in Django

Assuming you have a Job model and want to:

  • Show a list of all jobs on the homepage

  • Show details of a single job on a separate page


1. Create Views in jobs/views.py

from django.shortcuts import render, get_object_or_404

from .models import Job


# List all jobs

def homepage(request):

    jobs = Job.objects.all()  # Fetch all jobs

    return render(request, 'jobs/home.html', {'jobs': jobs})


# Detail view for a single job

def job_detail(request, job_id):

    job = get_object_or_404(Job, id=job_id)  # Get job or 404 if not found

    return render(request, 'jobs/job_detail.html', {'job': job})



2. Update portfolio/urls.py

Add URL patterns for both views:

from django.urls import path

from jobs import views


urlpatterns = [

    path('admin/', admin.site.urls),

    path('', views.homepage, name='home'),  # Homepage showing all jobs

    path('job/<int:job_id>/', views.job_detail, name='job_detail'),  # Detail page for job with ID

]



3. Update Templates

jobs/templates/jobs/home.html

List all jobs with clickable links to detail pages:

{% load static %}

<!DOCTYPE html>

<html>

<head>

    <title>All Jobs</title>

</head>

<body>

    <h1>All my jobs</h1>


    <ul>

    {% for job in jobs %}

        <li>

            <a href="{% url 'job_detail' job.id %}">{{ job.summary }}</a>

        </li>

    {% empty %}

        <li>No jobs found.</li>

    {% endfor %}

    </ul>

</body>

</html>



jobs/templates/jobs/job_detail.html

Show detailed info about a job:

{% load static %}

<!DOCTYPE html>

<html>

<head>

    <title>Job Detail</title>

</head>

<body>

    <h1>{{ job.summary }}</h1>

    <img src="{{ job.image.url }}" alt="{{ job.summary }}" height="300" />

    

    <p>More details about the job can go here.</p>


    <a href="{% url 'home' %}">Back to All Jobs</a>

</body>

</html>



Summary:

  • The homepage lists all jobs with links to their detail pages.

  • Clicking a job leads to a detail page showing more info.

  • URLs pass the job’s ID as a parameter to the detail view.

  • get_object_or_404 is used to safely get the job or return a 404 if missing.

Comments

Popular posts from this blog

Building an AI-Powered App with Next.js, Tailwind CSS, and OpenAI API

๐ŸŒ Build & Deploy a Website with Node.js and Express

✨ Build & Deploy a Stunning ReactJS UI Step by Step (Full Tutorial + Free Hosting)