Your First View
A view is a Python function that takes a request and returns a response.
Syntax
def view(request): return HttpResponse(...)A view is the code that runs for a URL. The simplest view is a function that accepts a request object and returns an HttpResponse.
Every view receives the request as its first argument. Whatever it returns becomes the HTTP response sent to the browser.
Example
# blog/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the blog!")
def detail(request, id):
return HttpResponse(f"You are viewing post {id}")When to use it
- A developer writes a function-based view that queries the database and returns a rendered HTML page.
- A developer returns a JSON response from a view to power a JavaScript frontend.
- A developer uses get_object_or_404 in a view to automatically return a 404 page when a record is missing.
More examples
Simple function-based view
A basic view that fetches all posts and renders them into an HTML template.
from django.shortcuts import render
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, "blog/post_list.html", {"posts": posts})Handle GET and POST methods
Branches on request.method to handle form submission separately from the initial page load.
from django.http import HttpResponse
def contact(request):
if request.method == "POST":
# process form
return HttpResponse("Thank you!")
return render(request, "contact.html")404 shortcut in a detail view
Uses get_object_or_404 to return a 404 response automatically when the post doesn't exist.
from django.shortcuts import get_object_or_404, render
from .models import Post
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, "blog/post_detail.html", {"post": post})
Discussion