Views

Function-Based Views (FBV)

Use function-based views for simple logic and straightforward endpoints. Keep views concise and focused on a single responsibility.

Example:

from django.shortcuts import render

def user_list(request):
    users = User.objects.all()
    return render(request, 'users/list.html', {'users': users})

Class-Based Views (CBV)

Use class-based views for reusable, extensible, and complex logic. Inherit from Django's generic views for common patterns (ListView, DetailView, CreateView, etc.).

Example:

from django.views.generic import ListView
from .models import User

class UserListView(ListView):
    model = User
    template_name = 'users/list.html'
    context_object_name = 'users'

View Organization

  • Group related views in app-specific files (e.g., views.py, views/ folder for large apps).
  • Use clear, descriptive names for views and endpoints.
  • Keep business logic out of views; use services or model methods for complex operations.

Best Practices

  • Use decorators (e.g., @login_required) for authentication and permissions.
  • Return appropriate HTTP responses and status codes.
  • Use context data for passing variables to templates.
  • Write tests for all views (unit and integration).
  • Document view responsibilities and expected inputs/outputs.