T
T
tema_sun2013-11-24 20:54:40
Django
tema_sun, 2013-11-24 20:54:40

How to save a local file in an ImageField in Django?

I am writing a new project on Django and finally decided to follow the TDD path. But I ran into a problem while testing the file upload. Because at the moment I don't have any forms yet, I just want to check the corresponding methods.
There is a class:

class Photos(models.Model):
    #*тут много чего опущено, но сути оно не меняет - в таком варианте тоже не работает
    photo_file = models.ImageField(upload_to=photos_storage)
    def add_photo(self, photo_file):
        with open(photo_file) as f:
            my_file = File(f)
            filename = "filename.jpg"
            self.photo_file.save(filename, my_file)

When checking the sizes of the source file and the uploaded one, I get:
AssertionError: 301202L is not 1830L
That is, only a fragment of the file gets into upload_to (I see that the fragment is because there is EXIF ​​at the beginning). I do not understand where to dig. Maybe when working with local files you need to do something else? Because if I take files from request.FILES it all works in another project.
I'm running Win7 if that matters. Django 1.5, Python 2.7.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tema_sun, 2013-11-24
@tema_sun

No, well, it's necessary. 2 hours fought and fought, but it was necessary to change the mode to binary.
You need to do open(photo_file, "rb")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question