Django休息框架ModelSerializer

时间:2013-11-26 08:20:18

标签: python django django-rest-framework

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_password中使用ModelSerializer


[编辑]

感谢您的回答〜!

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

我认为你的代码有问题。

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

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

所以我觉得有点尴尬。

1 个答案:

答案 0 :(得分:1)

您可以使用用户视图集并提供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)