Handle POST Request in DJANGO
I am new to DJANGO, and I am currently working on a project where I upload a file through a react page to a back-end handled by the DJANGO REST framework, after receiving the file I have to do some data processing.
After some research I found that this logic is supposed to be in the views.py
. So how do I create function which does this processing and how do I get it called whenever the server receives a new file or a POST request has been made.
views.py
from .models import FileStorage
from rest_framework import viewsets
from .serializers import FilesSerializer
class FileViewSet(viewsets.ModelViewSet):
queryset = FileStorage.objects.all()
serializer_class = FilesSerializer
You can override methods in your ViewSet
to add custom processing logic. It can be done like this:
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from .serializers import FilesSerializer
class FileViewSet(viewsets.ModelViewSet):
queryset = FileStorage.objects.all()
serializer_class = FilesSerializer
def perform_create(self, serializer):
# Access the uploaded file before saving
uploaded_file = self.request.FILES.get('file')
# Process the file
processed_data = self.process_file_before_save(uploaded_file)
# Save with additional processed data
if processed_data:
serializer.save(**processed_data)
else:
serializer.save()
def process_file_before_save(self, uploaded_file):
# Your processing logic here
# Return dict of additional fields to save
return {'processed_at': timezone.now()}
# If you don't want to save it just process
@action(detail=False, methods=['post'])
def process_file(self, request):
uploaded_file = request.FILES.get('file')
if not uploaded_file:
return Response(
{'error': 'No file provided'},
status=status.HTTP_400_BAD_REQUEST
)
try:
result = self.some_process_method(uploaded_file)
return Response({
'message': 'File processed successfully',
'filename': uploaded_file.name,
'size': uploaded_file.size,
'results': result
}, status=status.HTTP_200_OK)
except Exception as e:
return Response(
{'error': f'Processing failed: {str(e)}'},
status=status.HTTP_400_BAD_REQUEST
)