A Django view is a Python function or class that handles the logic for a specific web request. When a user accesses a URL, the corresponding view is called to process the request and return an appropriate response.
What is the Role of View?
Views act as the bridge between the user request and the data or response.
Process:
- It fetches data from the database (using models).
- Processes the data.
- Returns a response (HTML, JSON, file, etc.).
Types of Views in Django
1. Function-Based Views
Views written as Python functions.
Flexible and straightforward for simple tasks.
Example:
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, world!")
2. Class-Based Views
Views written as Python classes.
Built-in features like inheritance, mixins, and reusable methods.
Example:
from django.http import HttpResponse
from django.views import View
class HelloWorldView(View):
def get(self, request):
return HttpResponse("Hello, world!")
Create a Simple View
1. Open views.py
in your Django app.
2. Define a function-based view:
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to the home page!")
3. Map it to a URL in urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Rendering Templates in Views
Django views often render HTML templates using the render()
function:
Example:
from django.shortcuts import render
def home(request):
context = {'title': 'Home', 'message': 'Welcome to Django!'}
return render(request, 'home.html', context)
Class-Based Views (CBVs)
Django provides pre-built generic CBVs for common tasks:
TemplateView: Renders a template.
ListView: Displays a list of objects.
DetailView: Shows details for a single object.
Example:
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'home.html'
# In urls.py
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]