gpt4 book ai didi

django rest 框架 RetrieveUpdateAPIView

转载 作者:行者123 更新时间:2023-12-02 00:44:57 25 4
gpt4 key购买 nike

我来自越南。

我想通过 Django Rest FrameWork 更新用户。我可以通过“pk”更新用户。但我无法通过“用户名”更新用户。我希望每个人都帮助我。非常感谢。

序列化程序.py

class 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

View .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)

网址.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 Not Found

Allow: GET, HEAD, OPTIONS

Content-Type: application/json

Vary: Accept

{ "detail": "Not found." }

最佳答案

尝试像这样编辑您的 View ,

class UserUpdateAPIView(generics.RetrieveUpdateAPIView):
permission_classes = (permissions.IsAdminUser,)
serializer_class = UserUpdateSerialier
lookup_field = 'username'

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)

关于django rest 框架 RetrieveUpdateAPIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44432470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com