2

Django rest framework ModelSerializer

How to use ModelSerializer with User.

I just tried quickstart.

And it was good. But password is saved on the plain text.

$ 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'
>>>

Maybe ModelSerializer isn't use set_password.

So... What should I do in order to use set_password in ModelSerializer?


[EDIT]

Thank you for your answering~!

BTW, I have a question.

I think your code is something wrong.

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

User object is not created yet. But it call get_object in line 17.

So I think something is little bit awkward.

1 Answer 1

1

You could use a User ViewSet and provide a set_password action (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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Please see a question again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.