A
A
Alexander2016-04-14 18:36:19
Django
Alexander, 2016-04-14 18:36:19

What is wrong with uploading an image?

admin.py has a method:

def save_model(self, request, obj, form, change):
        obj.save()
        new_obj = Product.objects.latest('id')
        image = request.FILES
        Upload.upload_files(image, 'product', new_obj.id)

at the very end of the code, I
upload the upload_files image:
class Upload:
    def upload_files(files, folder_name, id):
        print(files)
        id = str(id)
        path = MEDIA_ROOT + '/images/' + folder_name + '/' + id
        if not os.path.exists(path):
            os.makedirs(path)
        for image in files:
            print(image)
            extensions = str(image).split('.')
            millis = str(round(time.time() * 1000))
            def process(f):
                with open(path + '/' + millis + extensions[-1],
                          'wb+') as destination:
                    for chunk in f.chunks():
                        destination.write(chunk)
            process(image)

print(files) :
<MultiValueDict: {'image': [<InMemoryUploadedFile: bicycle_wheel_drops_blur_101128_1440x900.jpg (image/jpeg)>, <InMemoryUploadedFile: change_admin.png (image/png)>]}>

print(image) :
image
Error in browser :
AttributeError at /admin/products/product/add/
'str' object has no attribute 'chunks'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Danil Biryukov-Romanov, 2016-04-14
@kentuck1213

You have the string "image" in the image, because there is an error in iterating over the dictionary in the for loop:

for image in files:
  ...

This is a 100% error when working with a dictionary, since the dictionary returns a key, value pair.
For a regular Dict, the loop would look like this:
for key, image in files:
  ...

However, how you use MultiValueDict here, I recommend that you refer to the Django documentation, most likely there is an example of use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question