def put(self, request, pk, format=None): client = self.get_object(pk) serializer = ClientSerializer(client, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def add_client(request): if request.method == 'POST': client_data = JSONParser().parse(request) client_serializer = ClientSerializer(data=client_data) if client_serializer.is_valid(): # Generate query cursor = connection.cursor() query = 'INSERT INTO clients_client(' data_spc_query = '' data_query = [] attrbs_table = list(client_data.keys()) for a in attrbs_table: if a != attrbs_table[-1]: query += a + ', ' data_spc_query += '%s, ' else: query += a + ') VALUES(' data_spc_query += '%s);' if a != 'password': data_query.append(client_data.get(a)) else: pwd = make_password(client_data.get(a)) data_query.append(pwd) query += data_spc_query print(query) cursor.execute(query, tuple(data_query)) connection.commit() return JsonResponse({ "code": 201, "message": "Client Added" }, status=status.HTTP_201_CREATED) return JsonResponse(client_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def client_detail(request, facebook_id): """ Retrieve, update or delete a code client. """ try: client = Client.objects.get(facebook_id=facebook_id) except Client.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ClientSerializer(client) log('client_detail', 'detail', 'detail user %s' % facebook_id) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = ClientSerializer(client, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': client.delete() log('client', 'delete', 'delete client %s' % facebook_id) return HttpResponse(status=204)
def post(self, request, format=None): client = ClientSerializer(data=request.data) if client.is_valid(): client = client.save() return Response(data={ 'client_id': client.client_id, }, status=status.HTTP_201_CREATED) return Response(client.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, pk): response = {} policy = ( Policy.objects.filter(pk=pk) .prefetch_related( "workstation_clients", "workstation_sites", "server_clients", "server_sites", ) .first() ) response["default_server_policy"] = policy.is_default_server_policy response["default_workstation_policy"] = policy.is_default_workstation_policy response["server_clients"] = ClientSerializer( policy.server_clients.all(), many=True ).data response["workstation_clients"] = ClientSerializer( policy.workstation_clients.all(), many=True ).data filtered_server_sites = list() filtered_workstation_sites = list() for client in policy.server_clients.all(): for site in client.sites.all(): if site not in policy.server_sites.all(): filtered_server_sites.append(site) response["server_sites"] = SiteSerializer( filtered_server_sites + list(policy.server_sites.all()), many=True ).data for client in policy.workstation_clients.all(): for site in client.sites.all(): if site not in policy.workstation_sites.all(): filtered_workstation_sites.append(site) response["workstation_sites"] = SiteSerializer( filtered_workstation_sites + list(policy.workstation_sites.all()), many=True ).data response["agents"] = AgentHostnameSerializer( policy.related_agents().only("pk", "hostname"), many=True, ).data return Response(response)
def client_detail(request, pk): """ Retrieve, update or delete a client. """ try: client = Client.objects.get(pk=pk) except Client.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ClientSerializerWithoutPassword(client) return JsonResponse(serializer.data) elif request.method == 'PATCH': data = request.data.copy() if 'lat' not in data: data['lat'] = None if 'lng' not in data: data['lng'] = None serializer = ClientSerializer(client, data=data, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=200) elif request.method == 'DELETE': client.delete() return HttpResponse(status=204)
class DocumentDetailSerializer(DocumentSerializer): from clients.serializers import ClientSerializer from projects.serializers import ProjectSerializer author = CRMUserTinySerializer(read_only=True) client = ClientSerializer() project = ProjectSerializer() task = ProjectTaskSerializer()
class AgentEditSerializer(serializers.ModelSerializer): winupdatepolicy = WinUpdatePolicySerializer(many=True, read_only=True) all_timezones = serializers.SerializerMethodField() client = ClientSerializer(read_only=True) custom_fields = AgentCustomFieldSerializer(many=True, read_only=True) def get_all_timezones(self, obj): return pytz.all_timezones class Meta: model = Agent fields = [ "id", "hostname", "client", "site", "monitoring_type", "description", "time_zone", "timezone", "check_interval", "overdue_time", "offline_time", "overdue_text_alert", "overdue_email_alert", "all_timezones", "winupdatepolicy", "policy", "custom_fields", ]
def get(self, request, pk): response = {} policy = (Policy.objects.filter(pk=pk).prefetch_related( "clients", "sites").first()) response["clients"] = ClientSerializer(policy.clients.all(), many=True).data filtered_sites = list() for client in policy.clients.all(): for site in client.sites.all(): if site not in policy.sites.all(): filtered_sites.append(site) response["sites"] = TreeSerializer(filtered_sites + list(policy.sites.all()), many=True).data response["agents"] = AgentHostnameSerializer(policy.related_agents(), many=True).data return Response(response)
class ContractSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(read_only=True) client = ClientSerializer(read_only=True) car = CarSerializer(read_only=True) payment_type_name = serializers.CharField(source='payment_type.name', read_only=True) class Meta: model = Contract fields = [ 'id', 'employee', 'client', 'car', 'date', 'payment_type', 'payment_type_name', 'price' ] def create(self, validated_data): employee = get_object_or_404(Employee.objects.all(), pk=self.context.get('employee_id')) car = get_object_or_404(Car.objects.all(), pk=self.context.get('car_id')) payment_type = get_object_or_404( PaymentType.objects.all(), pk=self.context.get('payment_type_id')) client = get_object_or_404(Client.objects.all(), pk=self.context.get('client_id')) contract = Contract.objects.create(price=validated_data.get('price'), car=car, employee=employee, payment_type=payment_type, client=client) return contract
def list(self, request, *args, **kwargs): queryset = Client.objects.filter(specialists=request.user) serializer = ClientSerializer(queryset, many=True, context={'request': request}) if request.user in User.objects.filter(groups__name='Specialists'): return Response(serializer.data) return super().list(request, *args, **kwargs)
class AlertTemplateRelationSerializer(ModelSerializer): policies = PolicySerializer(read_only=True, many=True) clients = ClientSerializer(read_only=True, many=True) sites = SiteSerializer(read_only=True, many=True) class Meta: model = AlertTemplate fields = "__all__"
class ProjectSerializer(ModelSerializer): """ serializes and deserializes projects to be sent over the network or saved in the database """ client = ClientSerializer() class Meta: model = Project fields = ['title', 'client', 'start_date', 'end_date', 'status']
def _handle_put(self, request, *args, **kwargs): """ PUT/PATCH handler for Client Detail Sample Post Data: { "name": "Detroit City Apartments" } """ client = self.get_object(kwargs.get('pk')) serializer = ClientSerializer(client, data=request.DATA) if serializer.is_valid(): serializer.save() return serializer.data return self.raise_bad_request(serializer.errors)
class PolicyTableSerializer(ModelSerializer): server_clients = ClientSerializer(many=True, read_only=True) server_sites = SiteSerializer(many=True, read_only=True) workstation_clients = ClientSerializer(many=True, read_only=True) workstation_sites = SiteSerializer(many=True, read_only=True) agents = AgentHostnameSerializer(many=True, read_only=True) default_server_policy = ReadOnlyField(source="is_default_server_policy") default_workstation_policy = ReadOnlyField(source="is_default_workstation_policy") agents_count = SerializerMethodField(read_only=True) winupdatepolicy = WinUpdatePolicySerializer(many=True, read_only=True) class Meta: model = Policy fields = "__all__" depth = 1 def get_agents_count(self, policy): return policy.related_agents().count()
class ProjectTeamClientSerializer(ProjectSerializer): team = TeamUserSerializer() client = ClientSerializer() has_tasks = serializers.SerializerMethodField() is_finished = serializers.SerializerMethodField() tasks_budget = serializers.SerializerMethodField() def get_has_tasks(self, obj): return obj.has_tasks() def get_is_finished(self, obj): return obj.is_finished() def get_tasks_budget(self, obj): return obj.tasks_budget()
def client_list(request): """ List all clients, or create a new client. """ if request.method == 'GET': clients = Client.objects.all() serializer = ClientSerializerWithoutPassword(clients, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) if 'password_hash' in data: data['password_hash'] = calc_hash(data['password_hash']) serializer = ClientSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=200)
def post(request): # Comprovem que l'usuari no sigui manager if request.data["is_manager"]: return Response("A client can not be manager", status=status.HTTP_400_BAD_REQUEST) # Creem l'usuari user = RegisterSerializer(data=request.data) user.is_valid(raise_exception=True) user.save() # Creem el client amb l'id i l'username de l'usuari client = { "_id": user.data["id"], "username": user.data["username"], "age": request.data.get('age', None), "country": request.data.get('country', None) } serializer = ClientSerializer(data=client) serializer.is_valid(raise_exception=True) serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED)
class ClientApi(APIView): @swagger_auto_schema( security=[], operation_description='Retrive all existing clients', operation_id='GET /clients', manual_parameters=[ openapi.Parameter(name='page', in_=openapi.IN_QUERY, default=1, type=openapi.TYPE_INTEGER, description='Page number'), openapi.Parameter(name='page_size', in_=openapi.IN_QUERY, default=50, type=openapi.TYPE_INTEGER, description='Number of page elements'), ], responses={ status.HTTP_200_OK: openapi.Response(description='Clients list', examples={ 'application/json': { 'count': openapi.TYPE_INTEGER, 'next': openapi.TYPE_STRING, 'previous': openapi.TYPE_STRING, 'results': [{ 'client_id': openapi.FORMAT_UUID, 'name': openapi.TYPE_STRING, 'cpf': openapi.TYPE_STRING, }] } }) }, ) def get(self, request, format=None): paginator = api_settings.DEFAULT_PAGINATION_CLASS() return paginator.get_paginated_response( queryset=Client.objects.all(), request=request, serializer=ClientDetailSerializer, serializer_kwargs={'fields': ( 'client_id', 'name', 'cpf', )}) @swagger_auto_schema( request_body=ClientSerializer(), security=[], operation_description='Create a client', operation_id='POST /clients', responses={ status.HTTP_201_CREATED: openapi.Response(description='Client has been created', examples={ 'application/json': { 'client_id': openapi.FORMAT_UUID } }), status.HTTP_400_BAD_REQUEST: openapi.Response(description='Fields are invalid', examples={ 'application/json_required': [{ 'field': 'This field is required' }], 'application/json_wrong': [{ 'field': 'Reason of the error' }] }) }) def post(self, request, format=None): client = ClientSerializer(data=request.data) if client.is_valid(): client = client.save() return Response(data={ 'client_id': client.client_id, }, status=status.HTTP_201_CREATED) return Response(client.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, *args, **kwargs): username = self.kwargs['username'] serializer = ClientSerializer( Clients.objects.filter(username=username), many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
def get(self, request, pk, format=None): client = self.get_object(pk) serializer = ClientSerializer(client) return Response(serializer.data)
def post(self, request, format=None): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400)
def get(request): serializer = ClientSerializer(Clients.objects.all(), many=True) return Response(data=serializer.data, status=status.HTTP_200_OK)
def list(self): queryset = Client.objects.all() serializer = ClientSerializer(queryset, many=True) return Response(serializer.data)
def get(self, request, format=None): clients = Client.objects.all() serializer = ClientSerializer(clients, many=True) return Response(serializer.data)