Django rest框架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。

所以我觉得有些尴尬。

最佳答案

您可以使用用户ViewSet并提供set_password操作(例如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)

10-06 08:04