我在DRF中保存了以下字段。發佈到Django Rest Framework時排除一些字段
- 生物
- 網站
- PHONENO
- 性別
- 阿凡達
我使用的反應母語作爲前端。在更新用戶配置文件時,我只想將更改發佈到服務器上。但是,在發佈到其餘api時,必須發佈formData中的所有值(包括頭像),並且由於頭像未更改,因此我試圖通過現有uri在服務器上似乎不起作用。 我試着創建另一個序列化程序,並使用PUT將數據傳遞給服務器,但無法正常工作。我不斷收到錯誤。
「細節」:「多重表單解析錯誤 - 在多無效的邊界:無」
這我猜可能是因爲傳遞的URI是無效的。我也嘗試在序列化程序中使用get_validation_exclusions()方法,但它也不起作用。如何在更新所有已更改的其他字段的同時將頭像發佈爲可選項?
views.py
class ProfileView(APIView):
serializer_class = ProfileSerializer
def get(self, request, format=None):
snippets = Profile.objects.filter(pk=request.user.id)
serializer = ProfileSerializer(snippets, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = ProfileSerializer(data=request.data)
if serializer.is_valid():
user= User.objects.get(pk=request.user.id)
user.profile.bio=request.data["bio"]
user.profile.website=request.data["website"]
user.profile.gender=request.data["gender"]
user.profile.phoneno=request.data["phoneno"]
user.profile.avatar=request.data["avatar"]
user.profile.save()
user.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, format=None):
snippet = User.objects.filter(pk=request.user.id)
serializer = ChangeProfileSeralizer(snippet, data=request.data)
if serializer.is_valid():
user= User.objects.get(pk=request.user.id)
user.profile.bio=request.data["bio"]
user.profile.website=request.data["website"]
user.profile.gender=request.data["gender"]
user.profile.phoneno=request.data["phoneno"]
user.profile.save()
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class ChangeProfileSeralizer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
fields = ('website', 'phoneno','gender','bio')
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
avatar=serializers.ImageField(max_length=None,use_url=True)
website = serializers.CharField(required=False)
phoneno = serializers.CharField(required=False)
gender = serializers.CharField(required=False)
avatar = serializers.ImageField(required=False)
class Meta:
model = Profile
fields = ('bio','website','phoneno','gender','avatar')
def get_validation_exclusions(self,instance=None):
exclusions = super(ProfileSerializer, self).get_validation_exclusions(instance)
return exclusions +['avatar']
編輯(剖面模型):
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True)
bio = models.TextField(max_length=500, blank=True)
website = models.TextField(max_length=200, blank=True)
phoneno = models.TextField(max_length=200, blank=True)
gender = models.TextField(max_length=200, blank=True)
avatar = models.ImageField('profile picture', upload_to='images/avatar/', default='/images/avatar/blank.png')
您是否嘗試在序列化程序中的頭像ImageField上設置'required = False',然後在發佈請求時僅排除字段? –