Django: how save bytes object to models.FileField? - python

My web application has the following structure:
backend with Django
frontend with React.
I have a form with React. I send a file from client form and I receive the file in my Django application with an APIView.
I receive a m3u file as bytes object.
b'------WebKitFormBoundaryIaAPDyj9Qrx8DrWA\r\nContent-Disposition:
form-data; name="upload";
filename="test.m3u"\r\nContent-Type: audio/x-
mpegurl\r\n\r\n#EXTM3U\n#EXTINF:-1 tvg-ID="" tvg-name="...
I would save the file in a Django model to a models.FileField and convert bytes object to m3u file.
How you do it?

models.FileField(models.ImageField) needs django.core.files.base.File like objects
ex)
django.core.files.base.File
django.core.files.images.ImageFile
File or ImageFile needs two args.
IO object : which has seek() method (ex) io.BytesIO).
name : str. (important! without name, it will not work).
bytes object doesn't have IO's methods(ex) seek()). it should be converted to IO object.
models.py
class Message(models.Model):
image = models.ImageField(upload_to='message_image/%Y/%m', null=True)
views.py or consumers.py or some-where.py
import io
from django.core.files.images import ImageFile
from myapp.models import Message
def create_image_message(image_bytes):
image = ImageFile(io.BytesIO(image_bytes), name='foo.jpg') # << the answer!
new_message = Message.objects.create(image=image)

You can try:
from django.core.files.base import ContentFile
import base64
file_data = ContentFile(base64.b64decode(fileData))
object.file.save(file_name, file_data)
You can use your file_name with an .m3u extension, and you shall have it.

I solved using temporary file. I used this code:
extM3u = str.encode(body.decode('utf8').split('EXTM3U\n#')[1].split('------WebKitFormBoundary')[0])
fileTemp = NamedTemporaryFile(delete=True, dir='media/tmp')
fileTemp.write(extM3u)
filenameRe = re.compile('.*?filename=[\'"](.*?)[\'"]')
filename = regParse(filenameRe, body.decode('utf8'))
file = File(fileTemp, name=filename)
m3u = M3u(titleField=filename, fileField=file)
m3u.save()

You can use a ContentFile. To do so:
from django.core.files.base import ContentFile
content_file = ContentFile(file_bytes, name=file_name)
# Assumes MyModel has a FileField called `file`
MyModel.objects.create(file=content_file)

convert string to bytes
bytes_data = ... # bytes
string_data = bytes_data.hex() # this is a string that you can save in TextField in django model
then, to get bytes from the string:
bytes_data_2 = bytes.fromhex(string_data)
I apologize for the crooked translation, I'm still only learning English.

Related

How to save python docx on client side using ajax?

I use python 3.6 Django, my code looks like this:
from docx import Document
document = Document()
document.add_heading('My docx', 0)
document.save('myFile.docx')
return HttpResponse(document, content_type='application/vnd')
I don't want to save it on server, instead I want to send it to client side using ajax and save it on client pc.
Any thoughts how to do it?
I was never in touch with ajax but I know how to present your file as a download without saving it in more as a temporary buffer.
You did not present the full function or method of your code. Therefore I am giving a get() method of a class-based view as an example.
Try this:
import io
from django.http import FileResponse
def get(self):
document = Document()
document.add_heading('My docx', 0)
buffer = io.BytesIO() # create buffer
doc.save(buffer) # save doc to buffer
buffer.seek(0) # returns the curser to the beginning of the bytestream
return FileResponse(buffer, as_attachment=True, filename=f"your_file.docx")
Read more about FileResponse here.

How to convert image address and save to imagefield in Django [duplicate]

please excuse me for my ugly english ;-)
Imagine this very simple model :
class Photo(models.Model):
image = models.ImageField('Label', upload_to='path/')
I would like to create a Photo from an image URL (i.e., not by hand in the django admin site).
I think that I need to do something like this :
from myapp.models import Photo
import urllib
img_url = 'http://www.site.com/image.jpg'
img = urllib.urlopen(img_url)
# Here I need to retrieve the image (as the same way that if I put it in an input from admin site)
photo = Photo.objects.create(image=image)
I hope that I've well explained the problem, if not tell me.
Thank you :)
Edit :
This may work but I don't know how to convert content to a django File :
from urlparse import urlparse
import urllib2
from django.core.files import File
photo = Photo()
img_url = 'http://i.ytimg.com/vi/GPpN5YUNDeI/default.jpg'
name = urlparse(img_url).path.split('/')[-1]
content = urllib2.urlopen(img_url).read()
# problem: content must be an instance of File
photo.image.save(name, content, save=True)
I just created http://www.djangosnippets.org/snippets/1890/ for this same problem. The code is similar to pithyless' answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn't perform any error handling by default so it's easy to get the contents of a 404/500 page instead of what you needed. You can create callback function & custom URLOpener subclass but I found it easier just to create my own temp file like this:
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(url).read())
img_temp.flush()
im.file.save(img_filename, File(img_temp))
from myapp.models import Photo
import urllib
from urlparse import urlparse
from django.core.files import File
img_url = 'http://www.site.com/image.jpg'
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
name = urlparse(img_url).path.split('/')[-1]
content = urllib.urlretrieve(img_url)
# See also: http://docs.djangoproject.com/en/dev/ref/files/file/
photo.image.save(name, File(open(content[0])), save=True)
Combining what Chris Adams and Stan said and updating things to work on Python 3, if you install Requests you can do something like this:
from urllib.parse import urlparse
import requests
from django.core.files.base import ContentFile
from myapp.models import Photo
img_url = 'http://www.example.com/image.jpg'
name = urlparse(img_url).path.split('/')[-1]
photo = Photo() # set any other fields, but don't commit to DB (ie. don't save())
response = requests.get(img_url)
if response.status_code == 200:
photo.image.save(name, ContentFile(response.content), save=True)
More relevant docs in Django's ContentFile documentation and Requests' file download example.
ImageField is just a string, a path relative to your MEDIA_ROOT setting. Just save the file (you might want to use PIL to check it is an image) and populate the field with its filename.
So it differs from your code in that you need to save the output of your urllib.urlopen to file (inside your media location), work out the path, save that to your model.
I do it this way on Python 3, which should work with simple adaptations on Python 2. This is based on my knowledge that the files I’m retrieving are small. If yours aren’t, I’d probably recommend writing the response out to a file instead of buffering in memory.
BytesIO is needed because Django calls seek() on the file object, and urlopen responses don’t support seeking. You could pass the bytes object returned by read() to Django's ContentFile instead.
from io import BytesIO
from urllib.request import urlopen
from django.core.files import File
# url, filename, model_instance assumed to be provided
response = urlopen(url)
io = BytesIO(response.read())
model_instance.image_field.save(filename, File(io))
Recently I use the following approach within python 3 and Django 3, maybe this might be interesting for others aswell. It is similar to Chris Adams solution but for me it did not work anymore.
import urllib.request
from django.core.files.uploadedfile import SimpleUploadedFile
from urllib.parse import urlparse
from demoapp import models
img_url = 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Stack_Overflow_logo.png'
basename = urlparse(img_url).path.split('/')[-1]
tmpfile, _ = urllib.request.urlretrieve(img_url)
new_image = models.ModelWithImageOrFileField()
new_image.title = 'Foo bar'
new_image.file = SimpleUploadedFile(basename, open(tmpfile, "rb").read())
new_image.save()
Just discovered that you don't have to generate a temporary file:
Stream url content directly from django to minio
I have to store my files in minio and have django docker containers without much disk space and need to download big video files, so this was really helpful to me.
Its been almost 11 years since the question and the most reputed answer has been posted. Thanks To #chris-adams for the response. I am Just reposting the same answer along with the updated packages and support.
#! /usr/bin/python3
# lib/utils.py
import urllib3 # http Request Package.
from typing import Optional
from django.core.files import File # Handle Files in Django
from django.core.files.temp import NamedTemporaryFile # handling temporary files.
def fetch_image(url: str, instance: models.Model, field: str, name: Optional[str]=None):
"""
fetch_image Fetches an image URL and adds it to the model field.
the parameter instance does not need to be a saved instance.
:url: str = A valid image URL.
:instance: django.db.models.Model = Expecting a model with image field or file field.
:field: str = image / file field name as string;
[name:str] = Preferred file name, such as product slug or something.
:return: updated instance as django.db.models.Model, status of updation as bool.
"""
conn = urllib3.PoolManager()
response = conn.request('GET', url)
if response.status <> 200:
print("[X] 404! IMAGE NOT FOUND")
print(f"TraceBack: {url}")
return instance, False
file_obj = NamedTemporaryFile(delete=True)
file_obj.write( response.data )
file_obj.flush()
img_format = url.split('.')[-1]
if name is None:
name = url.split('/')[-1]
if not name.endswith(img_format):
name += f'.{img_format}'
django_file_obj = File(file_obj)
(getattr(instance, field)).save(name, django_file_obj)
return instance, True
Tested with Django==2.2.12 in Python 3.7.5
if __name__ == '__main__':
instance = ProductImage()
url = "https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png"
instance, saved = fetch_image(url, instance, field='banner_image', name='intented-image-slug')
status = ["FAILED! ", "SUCCESS! "][saved]
print(status, instance.banner_image and instance.banner_image.path)
instance.delete()
this is the right and working way
class Product(models.Model):
upload_path = 'media/product'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
image_url = models.URLField(null=True, blank=True)
def save(self, *args, **kwargs):
if self.image_url:
import urllib, os
from urlparse import urlparse
filename = urlparse(self.image_url).path.split('/')[-1]
urllib.urlretrieve(self.image_url, os.path.join(file_save_dir, filename))
self.image = os.path.join(upload_path, filename)
self.image_url = ''
super(Product, self).save()

saving Base64ImageField Type using Django Rest saves it as Raw image. How do I convert it to a normal image

I have 5 image fields in my model , imageA, imageB, imageC, imageD and imageE
I am trying to save the images in the following manner.The image are of type Base64ImageField
images=["imageA","imageB","imageC","imageD","imageE"]
for field in images:
if field in serializer.validated_data:
content = serializer.validated_data[field]
dict = {field : content}
modelJob.objects.filter(id=modjob.id).update(**dict)
In the above code content contains the raw data.I am trying to update the image using the dict I created (the key is the field name and value is the content).
However the images saved in the imageField of the model are raw and not an actual image. How can I fix this ? This is what my serializer looks like
class Serializer_Custom_RX(serializers.ModelSerializer):
imageA = Base64ImageField(max_length=None, use_url=True, )
imageB = Base64ImageField(max_length=None, use_url=True, )
imageC = Base64ImageField(max_length=None, use_url=True, )
imageD = Base64ImageField(max_length=None, use_url=True, )
class Meta:
model = modelTest
fields = [
'title',
'zip',
'imageA','imageB','imageC','imageD',
]
More info:
If I do something like this
modelJob.instance.imageA.save(content=content,name="image.jpeg")
it works fine and the problem is solved.However there are two problems with this approach first of all I do not know the extension. How do I extract an extension ? I am just guessing a jpeg here and it works. The next thing is Ill have to check for imageA,B,C,D and E if they exist and then save each one individually. If I could come up with a dynamic solution close to something that I have that would work as well. This is what my jsondata looks like that I am posting
{
"title" : "Some Title",
"zip":12345,
"imageA":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUUEhMWFhUXGSIbGBgYGSIgHhogIB8fHSAbHyAeICghHR8lHh0dITElJSsrLi4uICAzODMsNygtLisBCgoKDg0OGxAQGy0lICUtLS01LS8tLS0tLS8vLy0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAKgBLAMBIgACEQEDEQH/xAAbAAACAgMBAAAAAAAAAAAAAAAFBgMEAAIHAf/EADwQAAIBAgUDAwMCBAUCBwEBAAECEQMhAAQSMUEFIlETYXEGMoFCkSOhscEUUmLR8Afh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bGYzFvql4s2T8UM9LoPr0aoQEI6sLmQpg2BFxuDB845p03IvVohqaMzoDq8KsbmeQQf3xmMxLD4Y21+hYx8Q50Oq4NNwwAMNpYxIncCL2Jv7DFv6ncNW21KpUm/tt7b8YzGYVdsbG7iyhWrNDFQdWrUSPG554XV+wxX6bnR6iyAqxpaQD2vIJv/qiRtjMZiuNJoawglSqilAzEUyQVB22KsFkwCsG35xQzrBxpYR3C/LR88W2EYzGYX+qxn0DurUdK038uwJtMAJA/mcEMjmgS2knUtMhSdzYGLbxP8sZjMWa5Q2Izc5liQ0drD2uY8jbFLMZ0qYifyMZjMShBOVUc0ls//9k="
}
The images encoding should come from the client, this is how you can know which format of each one has. Example:
base_64 = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739......
You will receive it from the client and you know that is a .gif
Once you have validated the extensions and the base64 you can convert it to images and save it in your OS:
Convert string in base64 to image and save on filesystem in Python or Decoding base64 from POST to use in PIL
Once you have the images in your OS, you can link them to your ImageField in the model changing the name property: Set Django's FileField to an existing file
I hope that is clear and helpful!!
Here is how I solved this problem. None of the answers above had this information
However there are two problems with this approach first of all I do
not know the extension.How do I extract an extension ?
The extension can be extracted by using the following code
from PIL import Image
decodedbytes = base64.decodebytes(str.encode(image_content))
image_stream = io.BytesIO(decodedbytes)
image = Image.open(image_stream)
filetype = image.format #Contains the extension
The next thing is Ill have to check for imageA,B,C,D and E if they
exist and then save each one individually. If I could come up with a
dynamic solution close to something that I have that would work as
well.
The solution to this was simple to use
getattr(job_inst, field).save(content=data , name="img"+filetype)
Short answer is :
import imghdr
extension = imghdr.what(file_name, decoded_file)
ref : https://docs.python.org/2/library/imghdr.html OR https://docs.python.org/3/library/imghdr.html
Basically import imghdr is the key in function Base64ImageField.get_file_extension to get / extract the extension of the function.
With below class extend / code you don't need to do modelJob.instance.imageA.save(content=content,name="image.jpeg")
You need to add this class in your codebase to call or for trial purpose you can add in same Serializer class file itself.
from django.core.files.base import ContentFile
import base64
import six
import uuid
class Base64ImageField(serializers.ImageField):
"""
A Django REST framework field for handling image-uploads through raw post data.
It uses base64 for encoding and decoding the contents of the file.
Heavily based on
https://github.com/tomchristie/django-rest-framework/pull/1268
Updated for Django REST framework 3.
"""
def to_internal_value(self, data):
# Check if this is a base64 string
if isinstance(data, six.string_types):
# Check if the base64 string is in the "data:" format
if 'data:' in data and ';base64,' in data:
# Break out the header from the base64 content
header, data = data.split(';base64,')
# Try to decode the file. Return validation error if it fails.
try:
decoded_file = base64.b64decode(data)
except TypeError:
self.fail('invalid_image')
# Generate file name:
file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
# Get the file name extension:
file_extension = self.get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
data = ContentFile(decoded_file, name=complete_file_name)
return super(Base64ImageField, self).to_internal_value(data)
def get_file_extension(self, file_name, decoded_file):
import imghdr
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
One more information is you can have
Base64ImageField(
max_length=None,
use_url=True,
required=False,
allow_null=True,
allow_empty_file=True
)
these params in case you want to make this optional.
NOTE :: I had got this code from StackOverflow only, but not remembered from where I got this I had liked this answer too.

Save Base64 String into Django ImageField

Im doing an application that uses Django in server-side.
Im trying to do that:
import uuid
from base64 import b64decode
from django.core.files.base import ContentFile
#staticmethod
def add_photo(user, person, image_base64):
photo = DatabasePersonPhoto()
photo.user = user
photo.person = person
image_data = b64decode(image_base64)
image_name = str(uuid.uuid4())+".jpg"
photo.image = ContentFile(image_data, image_name)
photo.save()
return photo
This is my Base64 String:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e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ErFUPUZpWvmUOYgUbBBBr2zaUou1ngSs1yg3qcsyI5TIBVVAE9ReNdHlB1SoT5BcQbST3GN25ILSg8kmtwR3xm4Lc81olKkHmSa3+MlK6eTzk01gk8KOpiSsJcSlO5FC6F9P5xq24h3WHG3KUhZoFO2522/8AMHonvy0hooUVKG6QDucsPws8OZusTWZcwqabJBbQBa1G6v2A6/F4KpJRQWEdzuXb4IaQ+zw9HipSUKCQlxJ7jerF7D3AF9/XLpiNtREtw2EFSyBzDuB7nAfCujM6JAbiRmgt8p2O5UkHqSf7vJpo0D6ZBDyi46TZcI6+g9q9Myql5OyGXJRWTONE5GQCbPXFjopF0aBHtiyvSAdT2VErrjOeaZ6A7H+MWLOOo/2R+zXl2sFSwlbJaKE8i07gDA+lnnff053/AHWG9kc+5SPnFizqo90RReSA8ZcP6ZIRMiOslTbIK2zzfckn3ylVQGQ0FWsnnI3rpXxixZraTtYpX5GKSQ4pI2AG1ZJeAdPi6hMkoloLqUVygnp1xYsZfawUe5F4eH/CmhR46pSILZeLlcygCR16ZbvCMCLHZckMtJStN1Q9jixYpU4Q1Dlkw4PUXFoeX9y3VHmJyWkf1J7VixYpT8g63cecoUATZOLFiywI/9k=
The image file is generated, but I cant open it like an image.
I think this will be a best approach tried it and tested in django 1.10. based on this SO answer: https://stackoverflow.com/a/28036805/6143656
I made a function for decoded base64 file.
def decode_base64_file(data):
def get_file_extension(file_name, decoded_file):
import imghdr
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
from django.core.files.base import ContentFile
import base64
import six
import uuid
# Check if this is a base64 string
if isinstance(data, six.string_types):
# Check if the base64 string is in the "data:" format
if 'data:' in data and ';base64,' in data:
# Break out the header from the base64 content
header, data = data.split(';base64,')
# Try to decode the file. Return validation error if it fails.
try:
decoded_file = base64.b64decode(data)
except TypeError:
TypeError('invalid_image')
# Generate file name:
file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
# Get the file name extension:
file_extension = get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
return ContentFile(decoded_file, name=complete_file_name)
Then you can call the function
import decode_base64_file
p = Post(content='My Picture', image=decode_based64_file(your_base64_file))
p.save()
I found the solution.
I need to use only the parte without data:image/jpeg;base64,
In Python, we can do it with something like this:
image_base64 = image_base64.split('base64,', 1 )
fh = open("imageToSave.png", "wb")
fh.write(imgData.decode('base64'))
fh.close()
Edit (klaus-d): The code above gives an example, how to store an image file from BASE64 encoded data. It opens a file imageToSave.png in binary mode for writing, then decodes the base64 image data and write the result to the file. At the end it closes the file descriptor.

Django download image from ImageField

I'm working with Django 1.7 and Python 3.4.
I have a model like this one:
class ImageModel(models.Model):
image = models.ImageField(verbose_name='image', upload_to='uploaded_images/')
Now I want to download image which is saved in /static/uploaded_images/.
For example I have a link like this: www.example.com/image/download/1, where 1 is id of ImageModel object.
Now i have a view:
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
( what I need to do? )
What next? How to create a view that will force download of that image?
You can try this code, maybe need some caveats:
from django.core.servers.basehttp import FileWrapper
import mimetypes
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
response['Content-Disposition'] = "attachment; filename=%s" % img.name
return response
I'm assuming there is a field .name in your ImageModel to get the name of the file in the second-to-last line ...filename=%s" % img.name You should edit the code to fit your project.
There is a field in an ImageField that is file, in the code here I use img.file to get the path to the file, you should change that for img.YOUR_IMAGE_FIELD.file or anything you need to get the path to the image
You need to use Content-Disposition header, take a look here:
Generating file to download with Django
Django Serving a Download File
A class based views-type exampe of this would be like this (i'm using python-magic to get the correct content-type for the file):
import os
import magic
from django.views.generic import View
from django.http import HttpResponse
from .models import ImageModel
class ImageDownloadView(View):
def get(self, request, *args, **kwargs):
image = ImageModel.objects.get(pk=self.kwargs['image_id'])
image_buffer = open(image.file.path, "rb").read()
content_type = magic.from_buffer(image_buffer, mime=True)
response = HttpResponse(image_buffer, content_type=content_type);
response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(image.file.path)
return response
This works for Django 1.10.7 but shouldn't be that different for Django 1.7
The other two answers are ok, but as advertised in many places using Django to serve an static file is not recommended for performance reasons. It is better to serve it using your web server (nginx/apache...).
You don't need an extra view to serve static files. Simply render a link to the file in your template:
Download this image!
Where object is an instance of ImageModel.
See django.db.models.fields.files.FieldFile.url
If you really want to have a view in an URL like www.example.com/image/download/1 you can simply write a view that redirect to the image URL obtained from the field.
Here is your cross browser safe download for files containing any character type
# Even better as it works in any browser (mobile and desktop)
def safe_name(file_name):
"""
Generates a safe file name, even those containing characters like ? and &
And your Kanji and Cyrillics are supported!
"""
u_file_name = file_name.encode('utf-8')
s_file_name = re.sub('[\x00-\xFF]', lambda c: '%%%02x' % ord(c.group(0)), u_file_name)
return s_file_name
# Handled by url(r'^/image/download/(\d+)/.+$
def safe_download_image(request, image_id):
"""
Safely downloads the file because the filename is part of the URL
"""
img = ImageModel.objects.get(id=image_id)
wrapper = FileWrapper(open(img.file)) # img.file returns full path to the image
content_type = mimetypes.guess_type(filename)[0] # Use mimetypes to get file type
response = HttpResponse(wrapper,content_type=content_type)
response['Content-Length'] = os.path.getsize(img.file)
# This works for most browsers, but IE will complain sometimes
response['Content-Disposition'] = "attachment;"
return response
def download_image(request, image_id):
img = ImageModel.objects.get(id=image_id)
redirect_do = safe_name(img.name)
return HttpResponseRedirect('/image/download/' + img_id + '/' + redirect_to)
It's doesn't work. I did something like this:
wrapper = FileWrapper(img.file) # img.file returns full path to the image
content_type = mimetypes.guess_type(str(img.file))[0] # Use mimetypes to get file type
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(str(img.file))
response['Content-Disposition'] = "attachment; filename=%s" % img.name
where img points to my ImageField field. File is downloaded, but I can't open it. xUbuntu image viewer seys 'Not a JPEG file. starts with 0x89 0x50'

Categories