What is a View?
In Django, a view is a Python function that takes a web request and returns a web response. That's it. Every page on your website is handled by a view. When someone visits a URL, Django finds the view mapped to that URL and runs it.
Views are where your business logic lives. They fetch data from the database, process it, and decide what to show the user. Think of views as the glue between your models and templates.
Function-Based Views
The simplest way to write a view is as a plain Python function. Every view function takes a request object as its first argument. The request object contains everything about the incoming HTTP request โ headers, method, body, user data, and more.
from django.http import HttpResponse
def hello_view(request):
return HttpResponse("Hello, World!")
A view must return an HttpResponse object. You can't just return a string. Django needs a proper response to send back to the browser.
Using render()
Returning raw text is fine for simple cases, but real applications need templates. The render() function combines a template with context data and returns an HttpResponse.
from django.shortcuts import render
def home_view(request):
context = {
'title': 'Welcome Home',
'username': 'Alice',
}
return render(request, 'home.html', context)
The render() function takes three arguments: the request object, the template name, and a dictionary of context data. This is the most common pattern you'll use.
Handling Different HTTP Methods
Views often need to handle both GET and POST requests differently. A GET request displays a form, while a POST request processes the submitted data.
from django.shortcuts import render
from django.http import HttpResponse
def contact_view(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
return HttpResponse('Message sent!')
return render(request, 'contact.html')
Always check request.method before processing form data. Never trust incoming data without validation.
Redirecting and Object Lookups
Sometimes you need to send users to a different page. The redirect() shortcut makes this easy. When you need to fetch a specific object from the database, get_object_or_404() saves you from writing boilerplate error handling.
from django.shortcuts import redirect, get_object_or_404
from django.http import HttpResponse
def post_detail(request, post_id):
post = get_object_or_404(Post, id=post_id)
return render(request, 'post_detail.html', {'post': post})
def post_list(request):
return redirect('home')
get_object_or_404() automatically returns a 404 page if the object doesn't exist. It's much cleaner than writing try/except blocks everywhere.