24π
β
Try str(uploaded_file.read())
to convert InMemoryUploadedFile
to str
uploaded_file = request.FILES['file']
print(type(uploaded_file)) # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
print(type(uploaded_file.read())) # <class 'bytes'>
print(type(str(uploaded_file.read()))) # <class 'str'>
UPDATE-1
Assuming you are uploading a text file (.txt
,.json
etc) as below,
my text line 1
my text line 2
my text line 3
then your view be like,
def my_view(request):
uploaded_file = request.FILES['file']
str_text = ''
for line in uploaded_file:
str_text = str_text + line.decode() # "str_text" will be of `str` type
# do something
return something
π€JPG
3π
file_in_memory -> InMemoryUploadedFile
file_in_memory.read().decode() -> txt output
- Django CharField without empty strings
- Django β Conditional Login Redirect
- Django: admin interface: how to change user password
0π
If you want to read file data as a list, then you can try out the following code:
uploaded_file = request.FILES['file']
file_data = uploaded_file.read().decode().splitlines() # get each line data as list item
π€Chirag Kalal
- Creating readable html with django templates
- Django, socket.io, node.js β Manage private messages and group conversations
- How to set value of a ManyToMany field in Django?
Source:stackexchange.com