在Django项目中,我有简单的UpdateAPIView
@Entity
public class Foo {
private Bar bar;
@Embedded
public Bar getBar () {
return ;
}
public void setBar (Bar bar) {
this.bar = bar;
}
}
@Embeddable
public class Bar {
private int bazzCount;
@Basic(fetch = FetchType.LAZY)
@Formula("(select count(*) from bazzes)")
public int getBazzCount () {
return bazzCount;
}
public void setBazzCount (int bazzCount) {
this.bazzCount = bazzCount;
}
}
和一个简单的模型
class ProfileUpdateAPIView(UpdateAPIView):
serializer_class = ProfileUpdateSerializer
authentication_classes = ( CsrfExemptSessionAuthentication, BasicAuthentication, TokenAuthentication,)
permission_classes = ((IsAuthenticated,))
它既不创建新文件也不更新profile_pic_field。尽管通过管理面板,它(图像)也可以轻松更新或创建
我的请求电话是
标题:
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)
身体:
Authorization:Token 7554057effce1fcbc313f9a96be99ae17efb8eaf
serializers.py
phone_number:92123123132
profile_pic :[[my file]]
答案 0 :(得分:1)
默认情况下,django-rest-framework
使用JSONParsor
。它不会解析上传的文件。要解析文件,我们必须像下面一样使用MultiPartParser
和FormParser
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)
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())
答案 1 :(得分:0)
我在定义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("")
我认为序列化程序只是用来在更新后显示响应。