def put(self, request, pk, format=None): Customer = self.get_object(pk) serializer = CustomerSerializer(Customer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): # serializer.save(user=self.get_queryset(request)) serializer.save() stripe_customer = stripe.Customer.create( email=request.user.email, description="My First Test Customer (created for API docs)", ) stripe.Customer.create_source( "cus_IEN4tSHEAoe1ZH", source="tok_mastercard", ) stripe.Charge.create( amount=2000, currency="inr", source="tok_mastercard", description="My First Test Charge (created for API docs)", ) send_email_task.delay() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) return Response({'serializer': serializer})
def create(self, request): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): customer = Customer() customer.name = serializer['name'].value customer.zipcode = serializer['zipcode'].value #Call BOB Api r = requests.get(BOB_API_URL.format(customer.zipcode)) if r.status_code == 200 and r.json()['results']: print("ZipCode found") ret = r.json()['results'][0] customer.street = ret['street'] customer.state = ret['state'] customer.city = ret['city'] else: print("zipCode not found on BOB_API") self.perform_create(customer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def customer_address(request, pk): try: customer = Customer.objects.get(pk=pk) except Customer.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = CustomerSerializer(customer) data = serializer.data data['name'] = data['firstname'] + ' ' + data['lastname'] return JsonResponse(data, safe=False) elif request.method == 'PUT': data = JSONParser().parse(request) firstname = data['firstname'] lastname = data['lastname'] tel = data['tel'] district = data['district'] subDistrict = data['subDistrict'] province = data['province'] postcode = data['postcode'] newAddress = firstname + '\\' + lastname + '\\' + district + '\\' + \ subDistrict + '\\' + province + '\\' + postcode + '\\' + tel putCustomer = Customer.objects.filter(pk=pk).update(address=newAddress) customer = Customer.objects.get(pk=pk) serializerPutCustomer = CustomerSerializer(customer) data = serializerPutCustomer.data data['name'] = data['firstname'] + ' ' + data['lastname'] return JsonResponse(data, status=201)
def post(self, request): try: # handling form or x-url-encoded-form data input request_body_dict = request.data.dict() except: # handling ray data request_body_dict = request.data serializer = CustomerSerializer(data=request_body_dict) try: if serializer.is_valid(): customer = serializer.save() customer_data = [{ 'id': customer.id, 'first_name': customer.first_name, 'last_name': customer.last_name, 'email': customer.email, 'dob': str(customer.dob) }] return HttpResponse(json.dumps({'data': customer_data}), status=status.HTTP_201_CREATED, content_type='application/json') return HttpResponse(json.dumps({'error': serializer.errors}), status=status.HTTP_400_BAD_REQUEST, content_type='application/json') except IntegrityError as ie: return HttpResponse(json.dumps({'error': str(ie.__cause__)}), status=status.HTTP_409_CONFLICT, content_type='application/json')
def post(self, request, id, format=None): serial = CustomerSerializer(data=request.data) if serial.is_valid(): serial.save() return Response(serial.data, status=status.HTTP_201_CREATED) return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, id, format=None): cust = self.get_object(id) serial = CustomerSerializer(cust, data=request.data) if serial.is_valid(): serial.save() return Response(serial.data, status=status.HTTP_201.CREATED) return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request): customer_profile = Customer.objects.get(mobile=request.user) serializer = CustomerSerializer(customer_profile, data=request.data) if serializer.is_valid(): serializer.save() response = {"msg": "OK"} status_code = status.HTTP_200_OK return Response(response, status=status_code) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def customer_add(request): # /cusAdd httpResponse/ ADD One if request.method == 'POST': customer_data = JSONParser().parser(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)
def createCustomer(self, request): try: data = JSONParser().parse(request) serializer = CustomerSerializer(data=data) if serializer.is_valid(): serializer.save() return self.generatePostSuccessResponse(self, serializer) return self.generateFormErrorResponse(self, serializer) except Exception as e: # return self.handleException(self, e) return JsonResponse(e, safe=False)
def put(self, request, pk, format=None): customer_object = self.get_object(pk) serializer = CustomerSerializer(customer_object, data=request.data) ElasticSearchService.store_customer_updation_query( request.data, 'customer', customer_object.id) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format = None): serializer = CustomerSerializer(data = request.data) if serializer.is_valid(): user = User(first_name = serializer.data['first_name'], \ last_name = serializer.data['last_name'], \ username = serializer.data['username'], \ email = serializer.data['email']) user.save() customer = Customer(user = user, city = serializer.data['city']) customer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
def customer(request): if request.method == 'GET': category=Customer.objects.all() serializer=CustomerSerializer(category,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 put(self, request, pk, format = None): customer = self.get_object(pk) self.check_object_permissions(self.request, customer) serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): user = customer.user user.first_name = serializer.data['first_name'] user.last_name = serializer.data['last_name'] user.email = serializer.data['email'] user.save() customer.city = serializer.data['city'] customer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_successful_retrieve_units_by_manager(self): """Test success retrieve units by manager""" Customer.objects.create( code='132', name='The first customer', contact_no='32152', address='New street', email='*****@*****.**' ) Customer.objects.create( code='134', name='The second customer', contact_no='32152', address='Old street', email='*****@*****.**' ) res = self.client.get(SUPPLIERS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) customers = Customer.objects.all().order_by('name') serializer = CustomerSerializer(customers, many=True) self.assertEqual(res.data, serializer.data)
class OrderSerializer(serializers.ModelSerializer): customer = CustomerSerializer(read_only=True) product = ProductSerializer(read_only=True) class Meta: model = Order fields = ["id", "customer", "product", "quantity", "created_at"]
class BillSerializer(serializers.ModelSerializer): items = BillItemSerializer(many=True, required=False) buyer = CustomerSerializer() seller = StaffSerializer() branch = BranchSerializer(read_only=True) payments = CustomerPaymentSerializer(many=True, required=False) price = serializers.ReadOnlyField() total_discount = serializers.ReadOnlyField() buyer_special_discount = serializers.ReadOnlyField() items_discount = serializers.ReadOnlyField() final_price = serializers.ReadOnlyField() paid = serializers.ReadOnlyField() cheque_paid = serializers.ReadOnlyField() card_paid = serializers.ReadOnlyField() cash_paid = serializers.ReadOnlyField() remaining_payment = serializers.ReadOnlyField() items_count = serializers.ReadOnlyField() profit = serializers.ReadOnlyField() class Meta: model = Bill fields = ('pk', 'bill_code', 'create_date', 'status', 'close_date', 'buyer', 'seller', 'discount', 'used_points', 'branch', 'payments', 'items', 'bill_image', 'price', 'total_discount', 'buyer_special_discount', 'items_discount', 'final_price', 'paid', 'cheque_paid', 'cash_paid', 'card_paid', 'remaining_payment', 'items_count', 'profit')
class CustomerChequeSerializer(serializers.ModelSerializer): customer = CustomerSerializer() class Meta: model = CustomerCheque fields = ('pk', 'number', 'bank', 'issue_date', 'expiry_date', 'amount', 'status', 'customer')
def test_successful_retrieve_customers_by_non_manager(self): """Test success retrieve customers by non-manager""" Customer.objects.create( code='135', name='The third customer', contact_no='32152', address='New street', email='*****@*****.**' ) Customer.objects.create( code='136', name='The fourth customer', contact_no='32152', address='Old street', email='*****@*****.**' ) self.client = APIClient() self.client.force_authenticate(self.cashier) res = self.client.get(SUPPLIERS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) customers = Customer.objects.all().order_by('name') serializer = CustomerSerializer(customers, many=True) self.assertEqual(res.data, serializer.data)
class ProjectSerializer(serializers.ModelSerializer): status = StatusProjectSerializer() customer = CustomerSerializer() mining_units = serializers.SerializerMethodField() detail_project_id = serializers.SerializerMethodField() def get_mining_units(self, obj): mining_units = [ project_detail.mining_init for project_detail in obj.project_detail_project.all() ] if len(mining_units) > 0: serializer = MiningUnitSerializer( mining_units, many=True, context={ 'detail_project': obj.project_detail_project.first().pk }) return serializer.data return [] def get_detail_project_id(self, obj): try: return obj.project_detail_project.first().pk except: return [] class Meta: model = Project exclude = ['consulting_company']
def fetch_data(request): user = request.user # try: customer = CustomerProfile.objects.get(user=user) context = CustomerSerializer(customer) context = context.data context = json.loads(JSONRenderer().render(context)) order = Order.objects.filter(customer=CustomerProfile.objects.get(user=user)).all().last() if order and not order.is_checked_out: items = ShopItem.objects.filter(order=order) for product in context['available_series']: cost = 0 for melody in product['melodies']: m = find_melody(items, product, melody) if m: melody['count'] = m.ordered_count cost += product['price'] * melody['count'] product['total_cost'] = cost promotions = Promotions.objects.filter(active=True).all() promotion_json = [] for p in promotions: promotion_json.append({ "description": p.description, "url": p.img.storage.base_location + '/' + p.img.name }) context["promotions"] = promotion_json return Response(context)
def customer_pic_profile(request, pk): try: customer = Customer.objects.get(pk=pk) except Customer.DoesNotExist: return HttpResponse(status=404) if request.method == 'POST': image = request.FILES['image'] filename_image, file_extension = os.path.splitext(image.name) nameImage = uuid.uuid4().hex + file_extension fs = FileSystemStorage() filename = fs.save(nameImage, image) storage_client = storage.Client() bucket_name = 'mejai' bucket = storage_client.bucket(bucket_name) blob = bucket.blob('customer/image/profile/' + nameImage) blob.upload_from_filename(filename=filename) blob.make_public() fs.delete(nameImage) newcustomerImage = Customer.objects.filter(pk=pk).update( picture=blob.public_url) customer = Customer.objects.get(pk=pk) serializerCustomer = CustomerSerializer(customer) return JsonResponse(serializerCustomer.data)
def customer_list(request): # /cusJson/ GET All if request.method == 'GET': customers = Customer.objects.all() customers_serializer = CustomerSerializer(customers, many=True) return JsonResponse(customers_serializer.data, safe=False)
class TransactionSerializer(serializers.ModelSerializer): customer = CustomerSerializer() category = CategorySerializer() bank_account = BankSerializer() class Meta: model = Transaction fields = '__all__'
def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): logger.info('Creating user %s started' % serializer.data['username']) user = User(first_name = serializer.data['first_name'], \ last_name = serializer.data['last_name'], \ username = serializer.data['username'], \ email = serializer.data['email']) user.set_password(serializer.data['password']) user.save() customer = Customer(user=user, city=serializer.data['city'], phone=serializer.data['phone']) customer.save() create_confirmations(customer) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class InvoiceSerlializer(serializers.ModelSerializer): customer = CustomerSerializer() class Meta: model = Invoice fields = ('id', 'buyerOrderNumber', 'buyerOrderNumberDate', 'taxInvoiceNumber', 'taxInvoiceNumberDate', 'deliverNumber', 'deliverNumberDate', 'qoutNumber', 'qoutNumberDate', 'subTotal', 'grandTotal', 'discount', 'status', 'residualPayment', 'customer')
def customer_detail(request, pk): # /cusJson with pk/ #Retrive one try: customer = Customer.objects.get(pk=pk) except Customer.DoesNotExist: return HttpResponse('customer not found.') if request.method == 'GET': customer_serializer = CustomerSerializer(customer) return JsonResponse(customer_serializer.data)
def get_customer(self, request): if Customer.objects.filter(is_attended=False).exists(): customer = Customer.objects.get_by_filter(is_attended=False)[0] print(customer.name) serializer = CustomerSerializer(customer) customer.is_attended = True customer.save() logger.info('Get customer success') return response.get_success_200( 'Customer details loaded successfully', serializer.data) logger.error(' No Customer data found ') return response.get_success_message('No data found')
def get_customer_authenticated(request): """ Retrieve customer instance given the auth token. """ try: user = request.user customer = Customer.objects.filter(user__id__iexact=user.id).first() except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CustomerSerializer(customer) return Response(serializer.data)
def profile(request): try: user = request.user customer = CustomerProfile.objects.filter(user=user)[0] context = CustomerSerializer(customer) context = json.loads(JSONRenderer().render(context.data)) return render(request, 'customer/profile.html', { 'name': customer.company_name, 'context': context }) except: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def customer(request): if request.method == 'GET': category = Customer.objects.all() serializer = CustomerSerializer(category, 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 customer_list(request): if request.method == 'GET': customer = Customer.objects.all() serializer = CustomerSerializer(customer, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CustomerSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)