python - Django 更改媒体文件 url 时无法设置属性

我正在创建一个函数,如果 image_type 更改,我希望文件的目录发生更改,例如,如果 image_typeaerial_view 它应该在 1 个文件夹中,如果它是 detailed_view 它应该移动给另一个。

该文件能够成功移动,但是我在更改图像的 url 时面临 can't set attribute

我不确定这是否是更改 MEDIA 文件文件夹的最佳方法,如果有更好的方法,我想提出建议。

def post(self, request):
        image_ids = dict((request.data).lists())['image_id']
        image_types = dict((request.data).lists())['image_type']
        arr = []

        for img_id, img_type in zip(image_ids, image_types):
            image_qs = RoofImages.objects.get(id=img_id)
            image_qs.image_type = img_type

            print(BASE_DIR)

            try:
                if image_qs.image_type == 'detailed_view':
                    full_image_url = f'{BASE_DIR}{image_qs.image.url}'
                    full_new_image_url = full_image_url.replace('aerial_view', 'detailed_view')
                    shutil.move(full_image_url, full_new_image_url)
                    image_qs.image.url = str(image_qs.image.url).replace('aerial_view', 'detailed_view')
            except Exception as e:
                print(e)

            try:
                if image_qs.image_type == 'aerial_view':
                    full_image_url = f'{BASE_DIR}{image_qs.image.url}'
                    full_new_image_url = full_image_url.replace('detailed_view', 'aerial_view')
                    shutil.move(full_image_url, full_new_image_url)
                    image_qs.image.url = str(image_qs.image.url).replace('detailed_view', 'aerial_view')
            except Exception as e:
                print(e)

            arr.append({img_id: img_type})

            image_qs.save()

        response_content = {
            'status': True,
            'message': 'Images type change successfully.',
            'result': arr
        }
        return Response(response_content, status=status.HTTP_201_CREATED)

回答1

稍微用谷歌搜索一下,我们可以使用 instance.field.name 而不是 instance.field.url 来更改属性。

try:
                if image_qs.image_type == 'detailed_view':
                    full_image_url = f'{BASE_DIR}{image_qs.image.url}'
                    full_new_image_url = full_image_url.replace('aerial_view', 'detailed_view')
                    shutil.move(full_image_url, full_new_image_url)
                    new_image_url = str(image_qs.image.url).replace('aerial_view', 'detailed_view')
                    image_qs.image.name = new_image_url
            except Exception as e:
                print(e)

            try:
                if image_qs.image_type == 'aerial_view':
                    full_image_url = f'{BASE_DIR}{image_qs.image.url}'
                    full_new_image_url = full_image_url.replace('detailed_view', 'aerial_view')
                    shutil.move(full_image_url, full_new_image_url)
                    new_image_url = str(image_qs.image.url).replace('detailed_view', 'aerial_view')
                    image_qs.image.name = new_image_url
            except Exception as e:
                print(e)

相似文章

最新文章