【发布时间】:2021-10-22 04:57:01
【问题描述】:
此处已提出类似问题:
- Update ImageField without forms in django,和
- Django ImageField is not updating when update() method is used
但答案始终是相同的(“改用.save()”)-此解决方案确实有效,但由于模型上的信号我无法控制,我想了解是否有任何替代方法可以使用。
# serializers.py
from drf_extra_fields.fields import Base64ImageField
from rest_framework import serializers
class ProfileSerializer(serializers.Serializer):
email = serializers.CharField(required=False, allow_null=True)
image = Base64ImageField(required=False, allow_null=True, max_length=None, use_url=True)
# views.py
def get_as_base64(url: AnyStr):
if url is None:
return None, None
full_name = url.split("/")[-1]
my_base = base64.b64encode(requests.get(url).content)
return my_base, full_name
def do_profile_update(profile: Dict):
b64_image, file_name = get_as_base64(profile.get("url"))
if b64_image and file_name:
*_, file_ext = file_name.split(".")
b64_image = f"data:image/{file_ext};base64,{b64_image.decode('utf-8')}"
build_dict = {
"email": profile.get("email"),
"image": b64_image,
}
serializer = ProfileSerializer(data=build_dict)
serializer.is_valid() # returns True
# serializer.validated_data = {'email': 'test@example.org', 'image': <SimpleUploadedFile: 11735acf-6d96-4c62-9e6a-8ebb7f7ea509.jpg (image/jpeg)>}
Profile.objects.filter(pk=pk).update(**serializer.validated_data) # This saves the *name* of the image to the database, but no image file
我了解 ImageField 基本上是 CharField,我可以在数据库中看到图像的名称,但图像没有写入服务器。
我的问题归结为:有没有办法单独将图像写入服务器,检索新保存图像的路径,并在.update()中使用?
TYIA。
【问题讨论】:
-
是否可以选择使用保存并以某种方式禁用信号?
-
不是真的,因为信号上有几个装饰器,即使我断开信号连接,它们似乎总是在运行
标签: django django-rest-framework django-orm