gpt4 book ai didi

python - Django 休息框架 ModelSerializer

转载 作者:太空宇宙 更新时间:2023-11-04 06:08:41 25 4
gpt4 key购买 nike

Django 休息框架 ModelSerializer

如何使用ModelSerializerUser .

我刚试过 quickstart .

这很好。但密码以明文形式保存。

$ pip freeze
Django==1.6
argparse==1.2.1
djangorestframework==2.3.9
wsgiref==0.1.2

$ curl -X post -d "username=lee&password=test" http://localhost:8081/users/
{"id": 4, "password": "test", "last_login": "2013-11-26T08:12:06.166Z", "is_superuser": false, "username": "lee", "first_name": "", "last_name": "", "email": "", "is_staff": false, "is_active": false, "date_joined": "2013-11-26T08:12:06.167Z", "groups": [], "user_permissions": []}

$ python manage.py shell
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
>>>
>>>
>>> from django.contrib.auth.models import User
>>> user=User.objects.get(username='lee')
>>> user.password
u'test'
>>>

也许 ModelSerializer不使用set_password .

所以...我应该怎么做才能使用set_passwordModelSerializer


[编辑]

谢谢你的回答~!

顺便说一句,我有一个问题。

我认为你的代码有问题。

https://gist.github.com/meoooh/7659801#file-gistfile1-py-L17

尚未创建用户对象。但是它在第 17 行调用了 get_object。

所以我觉得有点尴尬。

最佳答案

您可以使用 User ViewSet 并提供 set_password 操作(s. Marking extra methods for routing ):

from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from myapp.serializers import UserSerializer, PasswordSerializer

class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer

@action()
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.DATA)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

关于python - Django 休息框架 ModelSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20211743/

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