Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a FileField in Django REST Framework

I have this serializer which I am trying to test:

class AttachmentSerializer(CustomModelSerializer):
    order = serializers.PrimaryKeyRelatedField()
    file = FileField()

    class Meta:
        model = Attachment
        fields = (
            'id',
            'order',
            'name',
            'file_type',
            'file',
            'created_at',
        )

My test simply checks whether it is valid or not:

    def test_serializer_create(self):
        self.data = {
            'order': self.order.pk,
            'name': 'sample_name',
            'file_type': 'image',
            'created_at': datetime.now(),
            'file': open(self.image_path, 'rb').read()
        }

        serializer = AttachmentSerializer(data=self.data)

        self.assertTrue(serializer.is_valid())

And I am constantly getting this error:

{'file': ['No file was submitted. Check the encoding type on the form.']}

I tried to create a file in a number of different ways, such as with StringIO/BytesIO, File and etc. to no avail.

What might be wrong?

like image 408
Jahongir Rahmonov Avatar asked Oct 24 '25 00:10

Jahongir Rahmonov


1 Answers

from django.core.files.uploadedfile import SimpleUploadedFile
content = SimpleUploadedFile("file.txt", "filecontentstring")
data = {'content': content}

try smth like that , because if you check FileField serializer's code - it expects UploadedFile that should have name and size:

    def to_internal_value(self, data):
    try:
        # `UploadedFile` objects should have name and size attributes.
        file_name = data.name
        file_size = data.size
    except AttributeError:
        self.fail('invalid')

and StringIO or opened file objects doesn't have size attribute.

like image 100
Alexander Kamyanskiy Avatar answered Oct 26 '25 15:10

Alexander Kamyanskiy