[Django]-Using Django's test client, make a request using an in-memory file

7👍

Django comes with a set of wrappers for Python’s built-in file objects. In this situation django.core.files.base.ContentFile is suitable:

from django.core.files.base import ContentFile
file = ContentFile(b'content', name='plain.txt')
client.post('/', data={'file': file})

ContentFile expects to work with bytes, so don’t give it unicode data.

Another trick (if you don’t care about the content of the file) is to send the current file:

client.post('/', data={'file': open(__file__, 'rb'))

Leave a comment