我想更新配置文件實例用戶,通過將數據發送到URL update_profile/Django的REST框架創建配置文件實例,而不是更新檔案
我使用:
curl -X PUT -H "Authorization: Token sometoken" -d "name=somename&age=20&user=1" 127.0.0.1:8000/update_profile/
和錯誤我得到的是:{「user」:[「這個字段必須是唯一的。」]}
看起來錯誤是因爲請求創建了一個Profile的新實例,同一個用戶。但我只想更新用戶的當前配置文件實例。任何想法爲什麼我的代碼嘗試創建一個新的實例而不是更新它?
views.py
class UserProfileChangeAPIView(generics.UpdateAPIView, mixins.UpdateModelMixin):
permission_classes = (
permissions.IsAuthenticated,
UserIsOwnerOrReadOnly,
)
serializer_class = UpdateProfileSerializer
parser_classes = (MultiPartParser, FormParser,)
def get_queryset(self, *args, **kwargs):
queryset = Profile.objects.filter(user=self.request.user)
return queryset
def get_object(self):
self.request.user.profile
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
def update(self, request, pk=None):
try:
self.request.user.profile
except Http404:
return Response(
{'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
return super(UserProfileChangeAPIView, self).update(request, pk)
urls.py
url(r'^update_profile/$', UserProfileChangeAPIView.as_view(), name='update_profile'),
serializers.py
class UpdateProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = [
'name',
'age',
'user',
]
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, null=True)
age = models.PositiveIntegerField(null=True)
這似乎是ID不是問題的原因,因爲它是相同的用戶ID作爲用戶發送請求。如果我跳過序列化程序和放入數據中的用戶,則會出現此錯誤:NOT NULL約束失敗:rest_auth_profile.user_id – DevB2F