Exemple #1
0
 def put(self, request, pk):
     data = self.get_object(pk)
     serializer = CustomerSerializer(data, request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(status.HTTP_400_BAD_REQUEST)
Exemple #2
0
def login(request):
    login_data = JSONParser().parse(request)
    login_serializer = CustomerSerializer(data=login_data)
    if login_serializer.is_valid():
        login_serializer.save()
        return JsonResponse(login_serializer.data,
                            status=status.HTTP_201_CREATED)
    return JsonResponse(login_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
    def post(self, request):
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            response = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        return response
Exemple #4
0
def forgot(request):

    forgot_data = JSONParser().parse(request)
    forgot_serializer = CustomerSerializer(data=forgot_data)
    if forgot_serializer.is_valid():
        forgot_serializer.save()
        return JsonResponse(forgot_serializer.data,
                            status=status.HTTP_201_CREATED)
    return JsonResponse(forgot_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
    def test_create_customer(self):
        """Assert the CustomerSerializer successfully creates a new instance"""
        cust_with_addr_data = {k: v for k, v in self.customer_data.items()}
        cust_with_addr_data["address"] = self.address_data

        serializer = CustomerSerializer(data=cust_with_addr_data)
        self.assertTrue(serializer.is_valid())
        serializer.save()
        self.assertEqual(
            Customer.objects.filter(**self.customer_data).count(), 2)
 def put(self, request, pk):
     try:
         customer = Customer.objects.get(pk=pk)
     except Customer.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
     serializer = CustomerSerializer(customer,
                                     data=request.data,
                                     context={'request': request})
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #7
0
def customer_detail(request, pk):
    try:
        customer = Customer.objects.get(pk=pk)
    except Customer.DoesNotExist:
        exceptionError = {
            'message': "Not found a Customer with id = %s!" % pk,
            'customers': "[]",
            'error': "404 Code - Not Found!"
        }
        return JsonResponse(exceptionError, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':

        customer_serializer = CustomerSerializer(customer)
        return JsonResponse(customer_serializer.data)

    elif request.method == 'PUT':
        try:
            customer_data = JSONParser().parse(request)
            customer_serializer = CustomerSerializer(customer,
                                                     data=customer_data)

            if customer_serializer.is_valid():
                customer_serializer.save()
                response = {
                    'message':
                    "Successfully Update a Customer with id = %s" % pk,
                    'customers': [customer_serializer.data],
                    'error': ""
                }
                return JsonResponse(response)

            response = {
                'message': "Fail to Update a Customer with id = %s" % pk,
                'customers': [customer_serializer.data],
                'error': customer_serializer.errors
            }
            return JsonResponse(response, status=status.HTTP_400_BAD_REQUEST)
        except:
            exceptionError = {
                'message': "Fail to update a Customer with id = %s!" % pk,
                'customers': [customer_serializer.data],
                'error': "Internal Error!"
            }
            return JsonResponse(exceptionError,
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'DELETE':
        print("Deleting a Customer with id=%s" % pk)
        customer.delete()
        customer_serializer = CustomerSerializer(customer)
        response = {
            'message': "Successfully Delete a Customer with id = %s" % pk,
            'customers': [customer_serializer.data],
            'error': ""
        }
        return JsonResponse(response)
Exemple #8
0
def customer_list(request, format = None):
    """
    List all customers, or create a new customer_list
    """
    if request.method == 'GET':
        customers = Customer.objects.all()
        serializer = CustomerSerializer(customers, many = True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = CustomerSerializer(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 create(self, request, *args, **kwargs):
     data = request.data
     if isinstance(data['customer'], dict):
         cus_obj = Customer.objects.filter(mobile=data['customer']['mobile'])
         if not cus_obj:
             customer = CustomerSerializer(data=data['customer'])
             if customer.is_valid():
                data['customer'] = customer.save().id
         else:
             data['customer'] = cus_obj[0].id
     surv = SurveySerializer(data=data)
     if surv.is_valid():
         surv.save()
         return Response(surv.data, status=status.HTTP_201_CREATED)
     return Response(surv.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #10
0
 def get(self, request, *args, **kwargs):
     model_order = Orders.objects.all()
     serializer = self.serializer_class(model_order, many=True)
     for ser in serializer.data:
         user_model = CustomerSerializer(User.objects.get(id=ser['user_id']), many=False).data
         ser['user_details'] = user_model
     return response.Response(serializer.data, status=status.HTTP_200_OK)
    def get(self, request):
        data = []
        next_page = 1
        previous_page = 1
        customers = Customer.objects.all()
        page = request.GET.get('page', 1)
        paginator = Paginator(customers, 5)
        try:
            data = paginator.page(page)
        except PageNotAnInteger:
            data = paginator.page(1)
        except EmptyPage:
            data = paginator.page(paginator.num_pages)

        serializer = CustomerSerializer(data,
                                        context={'request': request},
                                        many=True)
        if data.has_next():
            next_page = data.next_page_number()
        if data.has_previous():
            previous_page = data.previous_page_number()

        return Response({
            'data':
            serializer.data,
            'count':
            paginator.count,
            'numpages':
            paginator.num_pages,
            'nextlink':
            '/api/customers/?page=' + str(next_page),
            'prevlink':
            '/api/customers/?page=' + str(previous_page)
        })
 def get(self, request, pk):
     try:
         customer = Customer.objects.get(pk=pk)
     except Customer.DoesNotExist:
         return Response(status=status.HTTP_404_NOT_FOUND)
     serializer = CustomerSerializer(customer, context={'request': request})
     return Response(serializer.data)
Exemple #13
0
    def get(self, request):
        customers = Customer.objects.all().order_by('customerName')
        serializer = CustomerSerializer(customers, many=True)
        responseData = serializer.data
        response = Response(responseData, status=status.HTTP_200_OK)

        return response
Exemple #14
0
def customer_detail(request, pk):
    print("custumer-detail", request.method)
    try:
        customer = Customer.objects.get(pk=pk)
    except Customer.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        customer_serializer = CustomerSerializer(customer)
        return JsonResponse(customer_serializer.data)

    elif request.method == 'PUT':
        print("reach here")
        customer_data = JSONParser().parse(request)
        customer_serializer = CustomerSerializer(customer, data=customer_data)
        if customer_serializer.is_valid():
            print("reach here2")
            customer_serializer.save()
            return JsonResponse(customer_serializer.data)
        return JsonResponse(customer_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        customer.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Exemple #15
0
class OrderSerializer(serializers.ModelSerializer):
    """
    Serializer for Read, Edit & Delete Orders
    """
    customer = CustomerSerializer(read_only=True)

    class Meta:
        model = Order
        fields = '__all__'
Exemple #16
0
def list_cart(user_id):
    customer_serializer = CustomerSerializer(User.objects.get(id=user_id),
                                             many=False)
    # loop list cart
    for dic in customer_serializer.data['carts']:
        dic['accessory_details'] = AccessorySerializer(
            accessory.objects.get(id=dic['accessory_id']), many=False).data
        # so tien
        dic['price'] = dic['qty'] * float(dic['accessory_details']['price'])
    return customer_serializer.data
Exemple #17
0
    def put(self, request, customer_id):
        try:
            token = request.META['HTTP_AUTHORIZATION']
            authenticated = authenticate(customer_id=customer_id, token=token)
        except KeyError:
            response = Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            if authenticated:
                customer = get_object_or_404(Customer, id=customer_id)
                serializer = CustomerSerializer(customer, data=request.data, partial=True)

                if serializer.is_valid():
                    serializer.save()
                    response = Response(serializer.data)
                else:
                    response = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
            else:
                response = Response(status=status.HTTP_401_UNAUTHORIZED)

        return response
Exemple #18
0
class OrderRetrieveSerializer(serializers.ModelSerializer):
    customer = CustomerSerializer()
    details = OrderDetailRetrieveSerializer(many=True, read_only=True)
    status = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = ('id', 'number', 'customer', 'status', 'details')

    def get_status(self, obj):
        return obj.get_status_display()
Exemple #19
0
class ClientSerializer(serializers.ModelSerializer):
    company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all(), required=False, write_only=True)
    customer = CustomerSerializer(many=True, required=False)

    class Meta:
        model = Client
        fields = ('id', 'company', 'name', 'account_number', 'mobile_number',
                  'landline_number', 'email', 'description', 'system_details', 'customer')

    def create(self, validated_data):
        return Client.objects.create_client(**validated_data, company=self.company)
Exemple #20
0
    def post(self, request):
        requestBody = request.data

        if not(requestBody is None):
            customerSerializer = CustomerSerializer(data=requestBody)

            if(customerSerializer.is_valid()):
                customer = Customer(**requestBody)
                Customer.save(customer)
                response = Response(customerSerializer.data,
                                    status=status.HTTP_200_OK)
            else:
                response = Response(
                    'Invalid Customer Details',
                    status=status.HTTP_400_BAD_REQUEST)
        else:
            response = Response(
                'Error', status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return response
    def test_serialize_customer(self):
        """Assert that CustomerSerializer successfully serializes an instance"""
        serializer = CustomerSerializer(self.customer)
        serialized_data = serializer.data
        address_data = serialized_data.pop("address")
        no_address_data = {
            k: v
            for k, v in self.customer_data.items() if k != "address"
        }

        self.assertDictEqual(serialized_data, no_address_data)
        self.assertDictEqual(address_data, self.address_data)
Exemple #22
0
    def test_create_customer_error(self):
        """
        Ensure we validate the data received.
        """
        url = reverse('customers:create-list-customers')
        data = {
            'first_name': '',
            'last_name': '',
            'phone': '',
            'address': '',
            'email': ''
        }

        serialized_data = CustomerSerializer(data=data)

        response = self.client.post(url, data, format='json')

        self.assertFalse(serialized_data.is_valid())
        self.assertJSONEqual(response.content, serialized_data.errors)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(Customer.objects.count(), 0)
Exemple #23
0
    def get(self, request):
        token = request.COOKIES.get('jwt')
        if not token:
            raise AuthenticationFailed('Unauthenticated User!')
        try:
            payload = decode_jwt(token)
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Login Again')
        user = Customer.objects.filter(id=payload['id']).first()
        serializer = CustomerSerializer(user)

        return Response({'data': serializer.data}, status=status.HTTP_200_OK)
Exemple #24
0
    def test_all_customers(self):
        response = self.client.get(reverse('customers_all'))
        expectedCustomers = Customer.objects.all().order_by('customerName')
        serializer = CustomerSerializer(expectedCustomers, many=True)

        expectedCustomersData = serializer.data
        actualCustomersData = response.data

        expectedStatusCode = 200
        actualStatusCode = response.status_code

        self.assertEqual(expectedStatusCode, actualStatusCode)
        self.assertEqual(expectedCustomersData, actualCustomersData)
Exemple #25
0
 def get(self, request, customer_id):
     try:
         token = request.META['HTTP_AUTHORIZATION']
         authenticated = authenticate(customer_id=customer_id, token=token)
     except KeyError:
         response = Response(status=status.HTTP_400_BAD_REQUEST)
     else:
         if authenticated:
             customer = get_object_or_404(Customer, id=customer_id)
             serializer = CustomerSerializer(customer)
             response = Response(serializer.data, status=status.HTTP_200_OK)
         else:
             response = Response(status=status.HTTP_401_UNAUTHORIZED)
     return response
Exemple #26
0
def customer_detail(request, pk, format = None):
    """
    Retrieve, update or delete a customer instance.
    """
    try:
        customer = Customer.objects.get(pk = pk)
    except Customer.DoesNotExist:
        return Response(status = status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CustomerSerializer(customer)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = CustomerSerializer(customer, data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status = status.HTTP_404_BAD_REQUEST)

    elif request.method == 'DELETE':
        customer.delete()
        return Response(status = status.HTTP_204_NO_CONTENT)
Exemple #27
0
 def get(self, request, *args, **kwargs):
     try:
         order_id = self.kwargs['id']
         model_order = Orders.objects.get(id=order_id)
         serializer = self.serializer_class(model_order, many=False).data
         user_model = CustomerSerializer(User.objects.get(id=serializer['user_id']), many=False).data
         serializer['user_details'] = user_model if user_model else None
         return response.Response(serializer, status=status.HTTP_200_OK)
     except ValidationError:
         return response.Response({'Message': '{} is not a valid UUID.'.format(self.kwargs['id'])},
                                  status=status.HTTP_400_BAD_REQUEST)
     except:
         return response.Response({'Message': 'Not found.'},
                                  status=status.HTTP_404_NOT_FOUND)
Exemple #28
0
    def test_get_customers(self):
        """
        Ensure all customers are returned
        """
        get_customers_url = reverse("customer_list")
        response = self.client.get(get_customers_url)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # get data from db
        customers = Customer.objects.all()
        serializer = CustomerSerializer(customers, many=True)
        self.assertEqual(response.data, serializer.data)

        self.assertEqual(len(response.data), 4)
Exemple #29
0
def register(request):
    # regData = JSONParser().parse(request)
    # customers_serializer = CustomerSerializer(regData, many=True)
    # return JsonResponse(customers_serializer.data, safe=False)

    register_data = JSONParser().parse(request)
    register_serializer = CustomerSerializer(data=register_data)

    # find tutorial by pk (id)
    try:
        tutorial = Customer.objects.get(email=register_data['email'])
    except Customer.DoesNotExist:
        register_serializer.is_valid()
        register_serializer.save()
        return JsonResponse(register_serializer.data,
                            status=status.HTTP_201_CREATED)

    if register_serializer.is_valid():
        register_serializer.save()
        return JsonResponse(register_serializer.data,
                            status=status.HTTP_201_CREATED)
    return JsonResponse(register_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Exemple #30
0
def customer_list(request):
    if request.method == 'GET':
        try:
          customers = Customer.objects.all()
          customers_serializer = CustomerSerializer(customers, many=True)

          response = {
             'message': "Get all Customers'Infos Successfully",
             'customers': customers_serializer.data,
             'error': ""
          }
          return JsonResponse(response, status=status.HTTP_200_OK);
        except: 
          error = {
            'message': "Fail! -> can NOT get all the customers List. Please check again!",
            'customers': "[]",
            'error': "Error"
          }
          return JsonResponse(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 
    elif request.method == 'POST':
        try:
            customer_data = JSONParser().parse(request)
            customer_serializer = CustomerSerializer(data=customer_data)
            
            if customer_serializer.is_valid():
                customer_serializer.save()
                print(customer_serializer.data)
                response = {
                   'message': "Successfully Upload a Customer with id = %d" % customer_serializer.data.get('id'),
                   'customers': [customer_serializer.data],
                   'error': "" 
                }
                return JsonResponse(response, status=status.HTTP_201_CREATED)
            else:
                error = {
                    'message':"Can Not upload successfully!",
                    'customers':"[]",
                    'error': customer_serializer.errors
                }
                return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
        except: 
            exceptionError = {
                    'message': "Can Not upload successfully!",
                    'customers': "[]",
                    'error': "Having an exception!"
                }
            return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR);
Exemple #31
0
def customer_list(request):
    if request.method == 'GET':
        customers = Customer.objects.all()
        customers_serializer = CustomerSerializer(customers, many=True)
        return JsonResponse(customers_serializer.data, safe=False)
        # In order to serialize objects, we must set 'safe=False'

    elif request.method == 'POST':
        customer_data = JSONParser().parse(request)
        customer_serializer = CustomerSerializer(data=customer_data)
        if customer_serializer.is_valid():
            customer_serializer.save()
            return JsonResponse(customer_serializer.data,
                                status=status.HTTP_201_CREATED)
        return JsonResponse(customer_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #32
0
def customer_list_age(request, age):
    try:
        customers = Customer.objects.filter(age=age)

        if request.method == 'GET':
            customers_serializer = CustomerSerializer(customers, many=True)
            response = {
                'message':
                "Successfully filter all Customers with age = %s" % age,
                'customers': customers_serializer.data,
                'error': ""
            }
            return JsonResponse(response, safe=False)
            # In order to serialize objects, we must set 'safe=False'
    except:
        exceptionError = {
            'message': "Fail to get a Customer with age = %s" % age,
            'customers': "[]",
            'error': "Raise an Exception!"
        }
        return JsonResponse(exceptionError,
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)