0

I am facing a problem while trying to send an array of images from the frontend(ReactJS) to the backend(Django). An object instance is not being saved at the backend because of the mandatory ArrayField in the Django Model. I am using PostgreSQL with Django. That's why I am able to use ArrayField.

I have already tried using a built-in (to_internal_value) method in the serializer to try to save the data I receive from the frontend.

https://www.django-rest-framework.org/api-guide/fields/

The following is a portion of the Django Model I have made:


...

lot_location_market = models.CharField(max_length=30, null=True, blank=False)

quality = models.CharField(max_length=250, null=True, blank=True)
remarks = models.CharField(max_length=250, null=True, blank=True)
layer_image = models.ArrayField(models.FileField(upload_to=get_file_path, null=False, blank=False))


I am using a Model Serializer. Serializer Code:


class FooSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)

    class Meta:
        model = Foo
        fields = (   
            ...
            'lot_location_market',
            'remarks',
            'quality',  
            'layer_image',
            )



I am using CreateAPIView (it extends CreateModelMixin and GenericAPIView)

The following is View for creating an instance of Foo from the API


class Foo(generics.CreateAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    lookup_field = 'id'
    serializer_class = FooSerializer

    def get_queryset(self):
        return Foo.objects.all()

    def perform_create(self, serializer):
        serializer.save()

1 Answers1

0

"Each serializer field class constructor takes at least these arguments." As pointed out in the documentation you linked.

I would have modeled your class a bit differently though. I would have created a separate class to handle the image upload and use a one to many fields. it makes rendering, displaying, and manipulation a lot easier to handle rather than go through a non-native sterilizer/validation.

class Foo(models.Model):
    some_stuff_for_foo=models.CharField()

class Bar:
    foo=models.ForeignKey(fFoo,on_delete=models.CASCADE,related_name='bar')
    image=models.FileField(upload_to=get_file_path, null=False, blank=False)
chrisroker0
  • 140
  • 2
  • 7