How to test a FileField in Django REST Framework
<p>I have this serializer which I am trying to test:</p>

<pre><code>class AttachmentSerializer(CustomModelSerializer):
    order = serializers.PrimaryKeyRelatedField()
    file = FileField()

    class Meta:
        model = Attachment
        fields = (
            'id',
            'order',
            'name',
            'file_type',
            'file',
            'created_at',
        )
</code></pre>

<p>My test simply checks whether it is valid or not:</p>

<pre><code>    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())
</code></pre>

<p>And I am constantly getting this error:</p>

<pre><code>{'file': ['No file was submitted. Check the encoding type on the form.']}
</code></pre>

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

<p>What might be wrong?</p>

<p>The thing is that you pass an opened file to the APIClient / APIRequestFactory, not to the view itself. The Django request will wraps the file to an <a href="https://docs.djangoproject.com/en/1.10/ref/files/uploads/#uploaded-files" rel="nofollow"><code>UploadedFile</code></a> which is what you should use.</p>

python django serialization django-rest-framework