def post(self, request, *args, **kwargs): """Delete machine.""" if not request.user.is_superuser: return ErrorMessage( "Only superusers are allowed to perform this action!").as_json data = json.loads(request.body.decode('utf-8'))['form'] form = DeleteMachineAPIForm(data) if form.is_valid(): try: cleaned_data = form.cleaned_data machine = Machine.objects.get( fqdn__iexact=cleaned_data['fqdn']) if machine.is_virtual_machine(): host = machine.get_hypervisor() if host.virtualization_api is None: return ErrorMessage( "No virtualization API found!").as_json if host.virtualization_api.remove(machine): result = machine.delete() else: result = machine.delete() theader = [ { 'objects': 'Deleted objects' }, { 'count': '#' }, ] response = { 'header': { 'type': 'TABLE', 'theader': theader }, 'data': [], } for key, value in result[1].items(): response['data'].append({ 'objects': key.replace('data.', ''), 'count': value }) return JsonResponse(response) except Exception as e: logger.exception(e) return ErrorMessage("Something went wrong!").as_json return ErrorMessage("\n{}".format( format_cli_form_errors(form))).as_json
def get(self, request, *args, **kwargs): """Return form for deleting a machine.""" if isinstance(request.user, AnonymousUser) or not request.auth: return AuthRequiredSerializer().as_json if not request.user.is_superuser: return ErrorMessage( "Only superusers are allowed to perform this action!").as_json form = DeleteMachineAPIForm() input = InputSerializer(form.as_dict(), self.URL_POST, form.get_order()) return input.as_json