Hello friends👋🏻
I was wondering how to use Celery workers for uploading files in django.
I tried implementing it on the ProductImage class we defined in the course by overriding the create method of our ProductImageViewSet.
But I found out the default json endcoder in django cannot serialize ImageFields.
Here’s my implementation. I would appreciate it if you guys can help:
serializers.py:
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = ['id', 'image']
tasks.py:
from time import sleep
from celery import shared_task
from .models import ProductImage
@shared_task
def upload_image(product_id, image):
print('Uploading image...')
sleep(10)
product = ProductImage(product_id=product_id, image=image)
product.save()
views.py:
this is the create method I tried to override:
def create(self, request, *args, **kwargs):
product_id = self.kwargs['product_pk']
image = self.request.FILES['image']
image.open()
image_data = Image.open(image)
upload_image.delay(product_id, image_data)
return Response('Thanks')