Django Views
Django Views Explained
Views are functions (or classes) that determine what response a user receives when they visit a page on your site. They serve as the bridge between browser requests and what’s displayed.
What Does a View Do?
When a user goes to a specific URL, Django checks the routing system and hands the request over to a view. That view then:
- Processes the request
- Collects or creates data
- Decides on the response
- Sends that result back to the browser
Basic View Example
Here’s a simple example using a function:
from django.http import HttpResponse
def welcome(request):
Return HttpResponse("Hello there! This is your homepage.") - request is the input from the user’s browser
- The response delivers a simple text message directly to the user's browser.
Location of Views
Typically, each app includes a views.py file where the response-handling functions are defined.
Sending HTML Pages
Instead of raw text, you can load an HTML file using Django’s rendering tool:
from django.shortcuts import render
def home(request):
Return render(request, 'home/index.html') - render() connects the request to a specific HTML template
- 'home/index.html' is the location of the layout file
Sending Context Data
Templates receive data through key-value pairs passed in as context from the view.
def contact(request):
Return render(request, 'home/contact.html', {'email': 'support@example.com'}) Then in your HTML, use:
<p>Contact us at {{ email }}</p>Class-Based Views
Besides functions, Django also supports class-style views for better structure and reuse.
Example:
from django.views import View
from django.http import HttpResponse
class HelloView(View):
def get(self, request):
Return HttpResponse("Hi! You're viewing a class-based page.")Choosing Between Function or Class
- Use functions for short, quick responses
- Pick classes for reusable or complex logic (e.g., login forms, permissions, etc.)
Attaching a View to a URL
You connect your view to a route inside urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.welcome),
path('contact/', views.contact),
] Summary
- Views respond to browser activity
- They can return text or full HTML pages
- You can use either function-style or class-style approaches
- Views live inside each app’s views.py
Prefer Learning by Watching?
Watch these YouTube tutorials to understand HTML Tutorial visually:
What You'll Learn:
- 📌 Why I Use Django Function Based Views
- 📌 #9 Django tutorials | Model View Template in Django | MVT