繁体   English   中英

Django中的UpdateAPIView不更新图像字段

[英]UpdateAPIView in Django not updating Image Field

在Django项目中,我有简单的UpdateAPIView

class ProfileUpdateAPIView(UpdateAPIView):
    serializer_class = ProfileUpdateSerializer
    authentication_classes = ( CsrfExemptSessionAuthentication, BasicAuthentication, TokenAuthentication,)
    permission_classes = ((IsAuthenticated,))

和一个简单的模型

def image_upload_fun(instance, filename):
    return 'profile_pics/user_{0}.{1}'.format(str(instance.phone_number),filename.split(".")[1])

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True)
    profile_pic = models.ImageField(upload_to=image_upload_fun, null=True, blank=True)
    phone_number = models.CharField(max_length=12, unique=True, null=False, blank=False)

这就是我打邮件的要求

它既不创建新文件也不更新profile_pic_field。尽管通过管理面板,它(图像)也可以轻松更新或创建


我的要求电话是

头:

Authorization:Token 7554057effce1fcbc313f9a96be99ae17efb8eaf

身体:

phone_number:92123123132
profile_pic :[[my file]]

serializers.py

class ProfileUpdateSerializer(serializers.ModelSerializer):
    profile_pic_url = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = ["name", "email", "phone_number","gender", "date_of_birth", "profile_pic_url"]

    def get_profile_pic_url(self, obj):
        try:
            return self.context["request"].build_absolute_uri("/").strip("/")+str(obj.profile_pic.url)
        except Exception as E:
            print(E)
            return str("")

默认情况下, django-rest-framework使用JSONParsor 它不会解析上传的文件。 要解析文件,我们必须使用MultiPartParserFormParser如下所示

from rest_framework.parsers import MultiPartParser, FormParser


class ProfileUpdateAPIView(UpdateAPIView):
    serializer_class = ProfileUpdateSerializer
    authentication_classes = (
        CsrfExemptSessionAuthentication,
        BasicAuthentication,
        TokenAuthentication
    )
    permission_classes = (IsAuthenticated,)
    parser_classes = (MultiPartParser, FormParser)

使用python请求进行请求

import requests

headers = {
  "Content-Type": "multipart/form-data",
  "Authorization": "Token <your token>"
}
data = {
    "phone_number": "987654231",
    "profile_pic": open("path/to/image.png", "r").read()
}

r = requests.post("http://localhost:8000/api/end-point/", data=data, headers=headers)
print(r.json())

我在定义ProfileUpdateSerializer的字段时犯了一个错误

我没有在序列化程序的字段中包含profile_pic字段

编辑序列化程序以添加“ profile_pic”字段可以上传图像

class ProfileUpdateSerializer(serializers.ModelSerializer):
    profile_pic_url = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = ["name", "email", "phone_number","gender", "date_of_birth", "profile_pic","profile_pic_url"]

    def get_profile_pic_url(self, obj):
        try:
            return self.context["request"].build_absolute_uri("/").strip("/")+str(obj.profile_pic.url)
        except Exception as E:
            print(E)
            return str("")

我以为串行器仅用于在更新后显示响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM