Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading InMemoryUploadedFile twice

I have an InMemoryUploadedFile object and when I make a .read() on it, it will lose its content.

Is it somehow possible to read this content twice from the same object? I tried to .copy() it, but of course that should not work.

If it is not possible, can I somehow put the content back to the same object?

Reason for this:

In a django form, a .prevalidation() method would read the content, but if it does, I can' t save it later on.

Performance here is not an issue.

like image 942
user2194805 Avatar asked Jun 23 '17 13:06

user2194805


2 Answers

You should be able to call seek(0) on the underlying file object:

my_file_obj.file.seek(0)
like image 170
Daniel Roseman Avatar answered Nov 16 '22 00:11

Daniel Roseman


Just adding to @Daniel Roseman answer.

Or you could just call my_file_obj.open() . It does the same thing.

Here is the code from Django's docs

    class InMemoryUploadedFile(UploadedFile):
        def open(self, mode=None):
            self.file.seek(0)
            return self

reference https://docs.djangoproject.com/en/3.0/_modules/django/core/files/uploadedfile/

like image 41
FYP Avatar answered Nov 15 '22 23:11

FYP