The Generic CRUD View in Django is a powerful tool for creating RESTful APIs with Create, Read, Update, and Delete functionalities. This user manual covers how to set up and use the Generic CRUD View, including configuring URLs, permissions, pagination, and views.
pip3 install django-api-helper
To create a CRUD view for your model, inherit from GenericCRUDView and specify the required attributes.
This view is used to create a generic CRUD view for any model.
It creates a view with the following endpoints:
- GET /api/model_name/ (List)
- GET /api/model_name/?pk=1 (Single)
- POST /api/model_name/ (Create)
- PATCH /api/model_name/?pk=1 (Update)
- DELETE /api/model_name/?pk=1 (Delete)
The following attributes must be defined in the child class: - permission_classes - filter_backends - filterset_class - model - pagination_class - serializer_class
from myapp.views import GenericCRUDView
from myapp.models import MyModel
from myapp.serializers import MyModelSerializer
from myapp.filters import MyModelFilterSet
class MyModelCRUDView(GenericCRUDView):
model = MyModel
serializer_class = MyModelSerializer
filterset_class = MyModelFilterSet
# Define other attributes like permission_classes, pagination_classSet up URL patterns to route requests to your CRUD view.
from django.urls import path
from myapp.views import MyModelCRUDView
urlpatterns = [
path('api/mymodel/', MyModelCRUDView.as_view(), name='mymodel-list'),
# Include other CRUD URLs
]Permissions can be managed at both table and object levels using decorators.
Use @check_table_permissions('app_name.permission_name') to check if the user has the necessary table-level permission.
Use @check_object_permissions('app_name.permission_name') for object-level permissions check.
Customize pagination by setting the pagination_class attribute in your view.
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 10
# Define other pagination settings
# In your CRUD view
class MyModelCRUDView(GenericCRUDView):
pagination_class = CustomPagination
# Other attributes...The CRUD view automatically provides endpoints for listing, retrieving, creating, updating, and deleting objects.
GET /api/model_name/
GET /api/model_name/?pk=1
POST /api/model_name/
PUT /api/model_name/?pk=1
DELETE /api/model_name/?pk=1
Leverage django-filter to provide advanced filtering capabilities. Define your filters in filterset_class.
The Generic CRUD View simplifies building RESTful APIs in Django, providing a robust and flexible framework for handling CRUD operations with ease.