👁️ Django Views – The Ultimate Guide to Handling Web Requests (2025)
🧲 Introduction – What Are Django Views?
In Django, views are Python functions (or classes) that process HTTP requests and return HTTP responses. They are the bridge between models (data) and templates (presentation), making them a central component of Django’s MVT architecture (Model-View-Template).
🎯 In this guide, you’ll learn:
- What a Django view is
- How to create function-based and class-based views
- How to link views with URLs
- Tips, examples, and real-world usage
🧪 What Is a Django View?
A view takes in a web request (e.g., from a browser) and returns a web response (e.g., an HTML page or JSON).
There are two types:
- Function-Based Views (FBVs)
- Class-Based Views (CBVs)
🛠️ Function-Based Views (FBV)
Here’s a simple example:
# blog/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, this is a Function-Based View!")
This view returns a plain-text response.
🌐 Linking Views to URLs
Create or update your app’s urls.py:
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Include it in your project’s main urls.py:
# mysite/urls.py
from django.urls import include, path
urlpatterns = [
path('blog/', include('blog.urls')),
]
Now visit: http://localhost:8000/blog/ ➝ You’ll see the response from your view.
🧱 Class-Based Views (CBV)
Class-based views provide reusable, extensible tools.
# blog/views.py
from django.http import HttpResponse
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("Hello from a Class-Based View!")
In urls.py:
from .views import HomeView
urlpatterns = [
path('class/', HomeView.as_view(), name='class-home'),
]
🧰 When to Use FBVs vs. CBVs
| Use Case | Recommendation |
|---|---|
| Simple logic (1–2 lines) | Function-Based Views |
| Reusable, extendable, form-based logic | Class-Based Views |
🔄 Common View Return Types
| Type | Function Used | Example Output |
|---|---|---|
| Plain Text | HttpResponse() | "Hello World" |
| Template | render() | Renders HTML with context |
| Redirect | redirect() | Redirects to another view/url |
| JSON | JsonResponse() | JSON-formatted API data |
📄 Using render() to Return HTML
from django.shortcuts import render
def homepage(request):
context = {'title': 'Welcome'}
return render(request, 'home.html', context)
✅ Best Practices for Django Views
- Use FBVs for simplicity and CBVs for complex/reusable logic
- Keep views thin (minimal logic); offload logic to services/helpers
- Always use
render()for HTML,JsonResponse()for APIs - Use decorators (like
@login_required) to add features
📌 Summary – Recap & Next Steps
🔍 Key Takeaways:
- Django views handle request/response logic in web apps
- FBVs are simple functions; CBVs are Python classes
- Views must be linked to URLs to be accessible
- Use
render()for templates andHttpResponse()for raw responses
⚙️ Real-World Relevance:
Views are how users interact with your site—whether you’re building a blog, store, dashboard, or API.
❓ Frequently Asked Questions (FAQ)
❓ What’s the difference between FBV and CBV?
✅ FBVs are Python functions, best for simple views. CBVs are classes and ideal for complex or reusable logic.
❓ Can a view return JSON?
✅ Yes. Use:
from django.http import JsonResponse
return JsonResponse({'key': 'value'})
❓ How do I restrict a view to logged-in users only?
✅ Use:
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
...
❓ Do views handle POST data?
✅ Yes. Use:
if request.method == 'POST':
data = request.POST['key']
❓ Can I pass data from views to templates?
✅ Yes. Use the context parameter in render():
return render(request, 'home.html', {'title': 'My Site'})
Share Now :
