What is a Django View?
In the Django MVT (Model-View-Template) architecture, the View is the 'controller' logic. It receives an HttpRequest, performs the necessary logic (like fetching data from a database or validating a form), and returns an HttpResponse. It acts as the bridge between your data (Models) and your presentation (Templates).
- Function-Based Views (FBV)
Function-Based Views are the simplest way to write views. They are just Python functions that take a request object as the first argument. They are excellent for simple logic and are highly readable.
- Class-Based Views (CBV)
As your project grows, you might find yourself repeating the same logic. Class-Based Views allow you to use inheritance and mixins to reuse code. Django provides generic views for common tasks like listing objects or showing details.
The Request-Response Lifecycle
Every view starts with a request and must end with a response. Django processes the request through middleware before it ever hits your view function.
FBV vs. CBV Comparison
| Feature | Function-Based Views | Class-Based Views |
|---|---|---|
| Complexity | Easy to understand | Requires OOP knowledge |
| Reusability | Limited (Harder to extend) | High (Inheritance & Mixins) |
| Control Flow | Explicit (if/else for methods) | Implicit (method-based: get, post) |
| Code Volume | More boilerplate | Very concise for standard tasks |
| Best For | Custom/Unique logic | CRUD operations & generic patterns |
Common View Shortcuts
- render(): Combines a template with a context dictionary and returns an HttpResponse.
- redirect(): Sends the user to a different URL (301 or 302 status).
- get_object_or_404(): Tries to get an object from a model; raises a 404 error if not found (cleaner than try/except).