Part 3: Introduction to Views and Template Rendering

kihuni

kihuni

Posted on May 9, 2024

Part 3: Introduction to Views and Template Rendering

What are Django Views?

Views in Django are Python functions or classes responsible for handling HTTP requests and returning HTTP responses. They encapsulate the logic of your application, connecting models to templates, processing user input, and determining what content to display.

In this guide, we will explore Django views, focusing on both Function-Based Views (FBVs) and Class-Based Views (CBVs), and discuss template rendering.

Functions-Based Views (FBVs)

Function-Based Views (FBVs) are defined as Python functions. They receive an HttpRequest object as input and return an HttpResponse object as output. In the context of a Task model, an FBV might fetch a task from the database and render a template with the task details.

# Example of function based

from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from .models import Task

def task_detail(request, task_id):
    task = get_object_or_404(Task, pk=task_id)
    return render(request, 'task_detail.html', {'task': task})

Enter fullscreen mode Exit fullscreen mode

Class-Based Views (CBVs):

Class-Based Views (CBVs) are defined as Python classes. They offer advantages like code reusability and better organization. Django provides built-in CBVs for common use cases. CBVs can handle different HTTP methods; through methods like get() and post().

from django.views import View
from django.shortcuts import render, get_object_or_404
from .models import Task

class TaskDetail(View):
    def get(self, request, task_id):
        task = get_object_or_404(Task, pk=task_id)
        return render(request, 'task_detail.html', {'task': task})

Enter fullscreen mode Exit fullscreen mode

Request and Response Objects:

The HttpRequest object represents an HTTP request received by the server, containing headers, cookies, and query parameters. The HttpResponse object is used to send an HTTP response back to the client, including content and metadata.

URL Routing and View Binding:

Django uses URL patterns to map URLs to views. URL patterns are defined in the project's URL configuration file (urls.py). Each pattern is associated with a view. Regular expressions are used to match incoming URLs with defined patterns.

from django.urls import path
from .views import task_detail,TaskDetail


urlpatterns = [
    path('task/<int:task_id>/', task_detail, name='task_detail'),
    path('task/<int:task_id>/', TaskDetail.as_view(), name='task_detail'),
]
Enter fullscreen mode Exit fullscreen mode

### Passing Data to Templates (Context):

To pass data from views to templates, use context. A context is a dictionary containing dynamic data retrieved from models, forms, or other sources in view. When rendering a template, the context is passed along with it.

from django.shortcuts import render
from .models import Task

def task_list(request):
    tasks = Task.objects.all()
    return render(request, 'task_list.html', {'tasks': tasks})

Enter fullscreen mode Exit fullscreen mode

Template Rendering:

Django's template engine facilitates the creation of HTML templates for dynamic content. Templates support placeholders for dynamic content insertion. Rendering templates is done using the render() function. Template inheritance allows the creation of base templates for reuse, preventing redundancy.

def task_detail(request, task_id):
    task = get_object_or_404(Task, pk=task_id)
    return render(request, 'task_detail.html', {'task': task})

class TaskDetail(View):
    def get(self, request, task_id):
        task = get_object_or_404(Task, pk=task_id)
        template_path = os.path.join(settings.BASE_DIR, 'tasks', 'templates', 'tasks', 'task_detail.html')
        return render(request, template_path, {'task': task})
Enter fullscreen mode Exit fullscreen mode

Example template

# task_details.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Task Detail</title>
</head>
<body>
    <h1>Task Detail</h1>
    <p><strong>Title:</strong> {{ task.title }}</p>
    <p><strong>Description:</strong> {{ task.description }}</p>
    <p><strong>Due Date:</strong> {{ task.due_date }}</p>
    <p><strong>Completed:</strong> {% if task.completed %}Yes{% else %}No{% endif %}</p>
    <p><strong>Created By:</strong> {{ task.created_by }}</p>
    <p><strong>Assigned To:</strong> {{ task.assigned_to }}</p>
    <p><strong>Created At:</strong> {{ task.created_at }}</p>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

To create dynamic web applications using Django, it is crucial to have a good understanding of Django views and template rendering. You can try experimenting with both Function-Based Views (FBVs) and Class-Based Views (CBVs) to see which approach works best for your project. Stay tuned for more insights on Django development in the upcoming series!

💖 💪 🙅 🚩
kihuni
kihuni

Posted on May 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related