我來自越南。django rest框架RetrieveUpdateAPIView
我想通過Django Rest FrameWork更新用戶。我可以通過'pk'更新用戶。但我無法通過'用戶名'更新用戶。我希望每個人都幫助我。非常感謝。
serializers.pyclass UserDetailSerializer(serializers.ModelSerializer):
url_update = serializers.HyperlinkedIdentityField(view_name='api:UserUpdateAPIView', lookup_field='username')
class Meta:
model = User
fields = ('url_update', 'username', 'email', 'user_permissions', 'is_staff', 'groups', 'last_login')
class UserUpdateSerialier(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'}
)
class Meta:
model = User
fields = ('pk', 'username', 'password')
def update(self, instance, validated_data):
instance.username = validated_data.get('username', instance.username)
instance.set_password(validated_data.get('password', instance.password))
instance.save()
return instance
views.py
class UserDetailAPIView(generics.RetrieveAPIView):
permission_classes = (permissions.IsAdminUser,)
serializer_class = UserDetailSerializer
#queryset = User.objects.all()
lookup_field = 'username'
def get_object(self):
username = self.kwargs["username"]
return get_object_or_404(User, username=username)
class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
permission_classes = (permissions.IsAdminUser,)
#queryset = User.objects.all()
serializer_class = UserUpdateSerialier
def get_object(self):
username = self.kwargs["username"]
return get_object_or_404(User, username=username)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
urls.py
url(r'^$', views.UserListAPIView.as_view(), name='UserListAPIView'),
url(r'^(?P<username>.*)/$', views.UserDetailAPIView.as_view(), name='UserDetailAPIView'),
url(r'^(?P<username>.*)/update/$', views.UserUpdateAPIView.as_view(), name='UserUpdateAPIView'),
HTTP 404未找到
允許:GET, HEAD,OPTIONS
內容類型:應用/ JSON
有所不同:接受
{ 「細節」: 「未找到」。 }
我添加lookup_field。但我無法更新用戶。 {「detail」:「找不到」。 } – Luan
我明白了。我編輯網址(?P。*)=>(?P [0-9A-Za-z _ \ - ] +)。我沒有添加looks_field。但我編輯網址。我完成了。 –
Luan