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! 🚀
View Decorators & Best Practices
Django provides decorators to add common functionality to views - restricting HTTP methods, requiring authentication, caching, and CSRF handling. Following best practices keeps your views clean, secure, and maintainable.
Common Decorators
- @require_http_methods(['GET', 'POST']) - Restrict allowed methods
- @require_GET - Only allow GET requests
- @require_POST - Only allow POST requests
- @login_required - Redirect unauthenticated users to login
- @permission_required('app.permission') - Check user permissions
- @csrf_exempt - Disable CSRF check (use carefully!)
- @cache_page(60*15) - Cache view output for 15 minutes
Decorators Example
# blog/views.py
# from django.contrib.auth.decorators import login_required, permission_required
# from django.views.decorators.http import require_http_methods, require_POST
# from django.views.decorators.cache import cache_page
# Restrict to specific methods
# @require_http_methods(["GET", "POST"])
# def contact(request):
# if request.method == 'POST':
# # Handle form
# return redirect('home')
# return render(request, 'contact.html')
# Require login
# @login_required(login_url='/accounts/login/')
# def dashboard(request):
# return render(request, 'dashboard.html')
# Require specific permission
# @permission_required('blog.add_post', raise_exception=True)
# def create_post(request):
# return render(request, 'blog/create.html')
# Cache page for 15 minutes
# @cache_page(60 * 15)
# def post_list(request):
# posts = Post.objects.all()
# return render(request, 'blog/list.html', {'posts': posts})
# Best Practices:
# 1. Keep views thin - move logic to models/services
# 2. Use get_object_or_404() instead of try/except
# 3. Always validate user input
# 4. Use named URLs, never hardcode paths
# 5. POST/Redirect/GET for form submissions
# 6. Separate concerns - views handle HTTP, not business logicTip
Tip
Use the Django shell (python manage.py shell) to test ORM queries interactively before putting them in views.
QuerySets are LAZY - no DB hit until evaluated.
Common Mistake
Warning
Not adding __str__ to models. Without it, the admin and shell show unhelpful 'Object (1)' instead of meaningful names.
Practice Task
Note
(1) Build a complete blog data model. (2) Test all CRUD operations in the shell. (3) Use aggregation for post statistics.
Quick Quiz
Key Takeaways
- Django provides decorators to add common functionality to views - restricting HTTP methods, requiring authentication, caching, and CSRF handling.
- @require_http_methods(['GET', 'POST']) - Restrict allowed methods
- @require_GET - Only allow GET requests
- @require_POST - Only allow POST requests