Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Redirects & HTTP Status Codes
Redirects send users to a different URL - essential after form submissions (POST/Redirect/GET pattern). HTTP status codes communicate the result of a request. Django provides convenient shortcuts for common redirect and response patterns.
HTTP Status Codes
- 200 OK - Request succeeded
- 201 Created - Resource created successfully
- 301 Moved Permanently - Permanent redirect (SEO)
- 302 Found - Temporary redirect (default in Django)
- 400 Bad Request - Invalid client request
- 403 Forbidden - Access denied
- 404 Not Found - Resource doesn't exist
- 500 Internal Server Error - Server-side error
Redirect Examples
# blog/views.py
# from django.shortcuts import redirect, render
# from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
# from django.urls import reverse
# redirect() shortcut - most common
# def create_post(request):
# if request.method == 'POST':
# post = Post.objects.create(title=request.POST['title'])
# # Redirect by URL name (recommended)
# return redirect('blog:post-detail', pk=post.pk)
# # Or redirect by URL string
# # return redirect('/blog/')
# POST/Redirect/GET pattern (prevents double submission)
# def submit_form(request):
# if request.method == 'POST':
# # Process form...
# return redirect('blog:post-list') # 302 redirect
# return render(request, 'blog/form.html')
# Permanent redirect (301) - for SEO
# def old_page(request):
# return HttpResponsePermanentRedirect('/new-page/')
# Custom status codes
# from django.http import HttpResponse
# def custom(request):
# return HttpResponse('Created', status=201)
# # return HttpResponse('Bad Request', status=400)Tip
Tip
Use select_related for ForeignKey (SQL JOIN) and prefetch_related for ManyToMany. Both eliminate N+1 query problems.
QuerySets are LAZY - no DB hit until evaluated.
Common Mistake
Warning
Not using select_related in views accessing related objects. Each template post.author access triggers a separate query without it.
Practice Task
Note
(1) Use django-debug-toolbar to count queries. (2) Add select_related and compare. (3) Use prefetch_related for M2M.
Quick Quiz
Key Takeaways
- Redirects send users to a different URL - essential after form submissions (POST/Redirect/GET pattern).
- 200 OK - Request succeeded
- 201 Created - Resource created successfully
- 301 Moved Permanently - Permanent redirect (SEO)