mcamacho
mcamacho

Reputation: 68

Upload picture to Django from Python script

I am having a bad time trying to upload an image to Django from a python script. I tried some solutions I found around but none works.

This is my simplified model:

class ExampleModel(models.Model):
    address = models.CharField(
        _('address'),
        max_length=200,
        blank=True,
    )
    photo = models.ImageField(
        verbose_name='photo',
        upload_to=path_for_photo,
        null=True,
        blank=True,
        validators=[FileValidator(max_size=settings.MAX_PHOTO_SIZE,
                              allowed_mimetypes=settings.ALLOWED_CONTENT_TYPES,
                              allowed_extensions=settings.ALLOWED_EXTENSIONS),]
)

Now, my view is like this:

def update(self, request, *args, **kwargs):
    instance = self.get_object()
    serializer = self.get_serializer(instance, data=request.data, partial=partial)
    serializer.is_valid(raise_exception=True)
    self.perform_update(serializer)
    return Response(serializer.data)

This is the script I have in Python:

with open('test.jpg', 'rb') as payload:
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    files = {
        'file': payload,
        'Content-Type': 'image/jpeg'
    }
    r = requests.put('http://localhost:8000/v1/myendpoint',
                      auth=('[email protected]', 'example'),
                      verify=False,  files=files, headers=headers)

But I don't know how to modify my update method to update images. I've tried a few approaches: send it as json (changing the 'content-type' and sending the info in 'data' parameter of requests.put), send it as InMemoryUploadedFile, and some other solutions that I've found googleing around.

I never thought that upload a simple image from Python would be that hard! I could do the same easily in a html form, but I need to put it from a python script.

Upvotes: 3

Views: 644

Answers (1)

blazaid
blazaid

Reputation: 91

Try this:

with open('test.jpg', 'rb') as payload:
    files = {
        'photo': payload,
        'Content-Type': 'image/jpeg'
    }
    r = requests.put(
        'http://localhost:8000/sendfiles/1/',
        verify=False, files=files
    )
    print(r)

Requests will see that "files" parameter has content and will set the headers accordingly.


Upvotes: 3

Related Questions