django-orchestra-test/orchestra/api/actions.py

31 lines
1.1 KiB
Python
Raw Normal View History

2014-05-08 16:59:35 +00:00
from rest_framework import status
from rest_framework.decorators import action
2014-05-08 16:59:35 +00:00
from rest_framework.response import Response
from .serializers import SetPasswordSerializer
class SetPasswordApiMixin(object):
@action(detail=True, methods=['post'], serializer_class=SetPasswordSerializer)
2014-05-08 16:59:35 +00:00
def set_password(self, request, pk):
obj = self.get_object()
data = request.data
2015-04-02 16:14:55 +00:00
if isinstance(data, str):
2014-10-15 12:47:28 +00:00
data = {
'password': data
}
2014-10-07 13:08:59 +00:00
serializer = SetPasswordSerializer(data=data)
2014-05-08 16:59:35 +00:00
if serializer.is_valid():
obj.set_password(serializer.data['password'])
2014-10-15 12:47:28 +00:00
try:
obj.save(update_fields=['password'])
except ValueError:
# Some services don't store the password on the database
# update_fields=[] doesn't trigger post save!
obj.save()
return Response({
'status': 'password changed'
})
2014-05-08 16:59:35 +00:00
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)