def accounts_modify(request): """ Function to manage the accounts modification """ # Creating the default value account = None # If not declared in settings, configuring a default value # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views try: nfe = settings.NON_FIELD_ERRORS_KEY except AttributeError: nfe = 'non_field_errors' # Parsing data from the request and changing the creator field for the user who did the request data = JSONParser().parse(request) data['creator'] = request.user.pk # Check if all the data is valid to be used serializer = AccountSerializer(data=data) if serializer.is_valid(): # If valid, try to get the model instance to check if already exists try: account = Account.objects.get(id=serializer.validated_data['id']) # Check if the creator is who did the request if request.user.pk == account.creator.pk: # If yes, allow to modify it serializer.update(account, serializer.validated_data) else: return Response( { 'errors': { nfe: 'No permissions', } }, status=status.HTTP_400_BAD_REQUEST, ) except Account.DoesNotExist: return Response( { 'errors': { nfe: 'Not exists', } }, status=status.HTTP_400_BAD_REQUEST, ) return Response({'status': 'ok', 'message': 'updated'})
def test_update(self): data = {'password': '******'} serializer = AccountSerializer(instance=self.account, data=data) serializer.update(self.account, data) account = Account.objects.get(pk='test_username') self.assertTrue(account.check_password('new_super_password'))