![]() |
VOOZH | about |
A core feature of Django is views, which define how data is presented to users. Views can be implemented in two main ways: Function-Based Views (FBVs) and Class-Based Views (CBVs).
FBVs are simple Python functions that receive a request, process it and return a response. They provide a straightforward way to handle HTTP requests.
Example: Creating a function-based view
In this example:
CBVs are Python classes that handle requests using object-oriented principles such as inheritance and mixins. They promote reusable and organized view logic, making it easier to manage complex views and avoid code duplication.
Example: Creating a class-based view
Note: Ensure that the template file 'form.html' exists inside your app's templates directory (e.g., templates/form.html), otherwise Django will raise a TemplateDoesNotExist error.
You can override class attributes dynamically when defining URL patterns:
Django’s generic CBVs provide pre-built views for common tasks like creating, updating, listing and deleting objects. They reduce boilerplate by automatically handling standard operations such as form display, validation, and saving.
In this example:
| Function-Based Views (FBVs) | Class-Based Views (CBVs) |
|---|---|
| Best for simple or one-off views with minimal logic. | Ideal for reusable or complex views. |
| Suitable for small, straightforward functionality. | Handles multiple HTTP methods or advanced logic cleanly. |
| Quick to prototype with minimal overhead. | Saves time with built-in generic views like CreateView, UpdateView, and DeleteView. |
| Provides full control over request handling. | Promotes reusable code using inheritance and mixins. |
| Example Use Cases: Contact form, simple data display, basic API endpoint | Example Use Cases: Blog post CRUD, user management, e-commerce product views |