【问题标题】:Django rest framework ModelSerializerDjango 休息框架 ModelSerializer
【发布时间】:2013-11-26 08:20:18
【问题描述】:

Django 休息框架ModelSerializer

如何使用ModelSerializer 和User。

我刚试过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。

那么...我应该怎么做才能在ModelSerializer 中使用set_password?


[编辑]

谢谢你的回答~!

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

我认为你的代码有问题。

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

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

所以我觉得有些尴尬。

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    您可以使用 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)
    

    【讨论】:

    • 谢谢!请再看一个问题!
    猜你喜欢
    • 2013-04-08
    • 2021-11-26
    • 1970-01-01
    • 2015-02-25
    • 2016-04-25
    • 2016-03-23
    • 2016-06-20
    相关资源
    最近更新 更多