def salarycreate(request): if request.POST: data = QueryDict.dict(request.POST) user = request.session['obj'] print(user) emp = Employee.objects.get(active_flag=True, employee_id=user, role='hr') if emp: form = SalaryCreateForm(data=data) data['user'] = user data['cost_to_company'] = int(data['cost_to_company']) data['basic_pay'] = ((data['cost_to_company']) * 40) / 100 data['hra'] = ((int(data['basic_pay']) * 40) / 100) data['pf'] = ((int(data['basic_pay']) * 24) / 100) data['bonus'] = round(((data['basic_pay'] * 8.33) / 100),2) data['special_allowance'] = round((data['cost_to_company']) - (data['basic_pay'] + data['hra'] + data['pf']),2) data['monthly_basic_pay'] = round((data['basic_pay']) / 12 ,2) data['monthly_hra'] = round((data['hra']) / 12 ,2) data['monthly_pf'] = round((data['pf']) / 12 ,2) data['monthly_bonus'] = round((data['bonus']) / 12 ,2) data['monthly_special_allowance'] = round((data['special_allowance']) / 12 ,2) data['monthly_salary'] = data['monthly_basic_pay'] + data['monthly_hra'] + data['monthly_pf'] + data['monthly_bonus'] + data['monthly_special_allowance'] print(data['monthly_salary'], type(data['monthly_salary'])) print(data['monthly_special_allowance'], type(data['monthly_special_allowance'])) if form.is_valid(): form.save() return JsonResponse({'message': 'Submitted'}) else: return JsonResponse(form.errors) else: return JsonResponse({'message': "no permission"}) form = SalaryDisplayForm() return render(request, 'add_salary.html', {'form': form})
def to_representation(self, instance): ret = super(LayerSerializer, self).to_representation(instance) group = instance.project.group # add attributes/fields ret['fields'] = self.get_attributes(instance) # add infoformat and infourl ret['infoformat'] = '' ret['infourl'] = '' # add bbox if instance.geometrytype != QGIS_LAYER_TYPE_NO_GEOM: bbox = self.qgis_projectsettings_wms.layers[ instance.name]['bboxes']['EPSG:{}'.format(group.srid.srid)] ret['bbox'] = {} for coord, val in bbox.items(): if val not in (float('inf'), float('-inf')): ret['bbox'][coord] = val else: if coord == 'maxx': ret['bbox'][coord] = -ret['bbox']['minx'] elif coord == 'maxy': ret['bbox'][coord] = -ret['bbox']['miny'] elif coord == 'minx': ret['bbox'][coord] = -ret['bbox']['maxx'] else: ret['bbox'][coord] = -ret['bbox']['maxy'] # add capabilities ret['capabilities'] = self.get_capabilities(instance) # add styles ret['styles'] = self.qgis_projectsettings_wms.layers[ instance.name]['styles'] ret['source'] = {'type': instance.layer_type} # add options for wms layer if instance.layer_type == 'wms': datasourceWMS = QueryDict(instance.datasource) if 'username' not in ret['source'] or 'password' not in ret[ 'source']: ret['source'].update(datasourceWMS.dict()) ret['source']['external'] = True #ret['servertype'] = MSTYPES_OGC # add proj4 ret['proj4'] = G3WSpatialRefSys.objects.get(srid=ret['crs']).proj4text # add metadata ret['metadata'] = self.qgis_projectsettings_wms.layers[ instance.name]['metadata'] # eval editor_form_structure if ret['editor_form_structure']: ret['editor_form_structure'] = eval(instance.editor_form_structure) return ret
def leaveapplycreate(request): if request.method == 'POST': user = request.session['obj'] data = QueryDict.dict(request.POST) form = Leaveapplyform(data) data['by'] = user if form.is_valid(): obj = form.save(commit=False) d1 = datetime.strptime(data['to_date'], '%Y-%m-%d').date() d2 = datetime.strptime(data['from_date'], '%Y-%m-%d').date() delta = d1 - d2 obj.days = delta.days + 1 obj.save() form.save() return HttpResponse('sunnam success') else: user = request.session['obj'] lead_obj = Employee.objects.get(id=user) lead = lead_obj.reporting_lead lead_name = Employee.objects.get(id=lead) hr = Employee.objects.filter(role="hr").order_by('id')[0] superuser = Employee.objects.filter(role="su").order_by('id')[0] leads = {'lead': lead_name, 'hr': hr, 'superuser': superuser} form = Leaveapplyform(leads=leads) return render(request, 'leaveapply.html', {'form': form})
def salary_revision(request, pk): user = request.session['obj'] emp = Employee.objects.get(active_flag=True, id=user) data = QueryDict.dict(request.POST) if emp.role == 'hr' or 'su': salary = Salarydetails.objects.get(pk=pk) print(salary) # print(sal.monthly_basic_pay) form = SalaryRevisionForm(data=data) # print(form['monthly_basic_pay']) print(form['per']) # percent = request.POST['percent'] if request.POST: if form.is_valid(): form.save() return redirect(salary_revision) else: print(form.errors) form = SalaryRevisionDisplayForm() # print(form['per']) return render(request, 'salary_revision.html', {'form': form}) else: return HttpResponse({"no perission"})
def change_password(request): """ change password""" user = request.session['obj'] data = QueryDict.dict(request.POST) obj = get_object_or_404(Employee, active_flag=True, id=user) print(obj.employee_id) if request.POST: form = Changepasswordform(data=data) if form.is_valid(): print(form['password']) if obj.check_password(data['password']): new_password = data['new_password'] re_enter_new_password = data['re_enter_new_password'] if new_password == re_enter_new_password: obj.password = new_password obj.set_password(obj.password) obj.save() return JsonResponse({'message': "password changed"}) else: return JsonResponse({'message': 'new password and confirm new password doesn\'t match'}) else: return JsonResponse({'message': 'Please enter old password correctly'}) form = Changepasswordform() return render(request, 'changepassword.html', {'form': form})
def post(self, request): query_dict = QueryDict.dict(request.data) url = "https://login.bol.com/token?grant_type=client_credentials" payload = { 'client_id': query_dict['client_id'], 'client_secret': query_dict['client_secret'], 'grant_type': 'client_credentials' } headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) if response.status_code == 200: res_data = response.json() query_dict['access_token'] = res_data["access_token"] serializer = SellerProfileCreateSerializer(data=query_dict) if serializer.is_valid(): serializer.save() return Response(format_response(serializer.data, status.HTTP_201_CREATED), status=status.HTTP_201_CREATED) return Response(format_response(custom_error(serializer.errors), status.HTTP_400_BAD_REQUEST), status=status.HTTP_400_BAD_REQUEST) else: return Response(format_response(error_message(invalid_client_id), status.HTTP_400_BAD_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def filter(self, request): """ To filter the purchase model data """ data = QueryDict.dict(request.data) if 'date' in data and data['date']: status = ['open', 'verified', 'dispatched', 'delivered'] if self.model.get_latest().get_status() == 'dispatched': status = ['dispatched'] elif self.model.get_latest().get_status() == 'delivered': dispatched_exist = self.model.check_dispatched_status_exist() if dispatched_exist: status = ['dispatched'] else: status = ['delivered'] queryset = self.model.get_filter_data(data['date'], status) else: queryset = self.model.get_filter_data() queryset = sorted(queryset, key=lambda x: x['month']) data = { 'xAxis': list(map(lambda x: calendar.month_name[int(x['month'])], queryset)), 'yAxis': list(map(lambda x: x['count'], queryset)) } return Response(data)
def monthly_pay(request, pk): emp = get_object_or_404(Salarydetails, pk=pk) employee_id=emp.emp_id.employee_id print(emp.emp_id.id) sal = Salarydetails.objects.filter(pk=emp.id) # print(sal.monthly_basic_pay) if request.POST: data = QueryDict.dict(request.POST) data['emp_id'] = emp.emp_id.id data['basic_pay'] = emp.monthly_basic_pay data['hra'] = emp.monthly_hra data['bonus'] = emp.monthly_bonus data['special_allowance'] = emp.monthly_special_allowance data['pf'] = emp.monthly_pf data['esi'] = emp.monthly_esi data['earning'] = (float(data['basic_pay']) + float(data['hra']) + float(data['bonus']) + float(data['special_allowance'])) data['deduction'] = (float(data['pf']) + float(data['esi'])) data['total_income'] = (int(data['earning']) - int(data['deduction'])) form = MonthlyslipForm(data=data) print(data['emp_id']) if form.is_valid(): # data['emp_id'] = emp.emp_id.id form.save() return redirect(employee_select) else: return JsonResponse(form.errors) form = MonthlyslipDisplayForm() return render(request, 'add_payslip.html', {'sal':sal, 'form': form})
def update(self, request, id, *args, **kwargs): """ To update the particular movie booked URL Structure: /movie/book/1/ Required Fields: `id`, 'user', 'show', 'seat_class', 'seat_number', 'no_of_tickets', 'service_fee', 'total_cost' """ try: queryset = self.model.objects.get(id=id, active=True) except: return Response({'message': 'Not exist'}, status=400) data = QueryDict.dict(request.data) data['user'] = request.user.pk serializer = self.serializer_class(queryset, data=data, partial=True) if serializer.is_valid(): obj = serializer.save() obj.service_fee = obj.no_of_tickets * 30 obj.total_cost = obj.service_fee + (obj.no_of_tickets * obj.seat_class.cost_per_ticket) obj.save() return Response(serializer.data) return Response(serializer.errors, status=400)
def create(self, request): """ To create the movies URL Structure: /movie/ Required Fields: 'name', 'director', 'genre', 'popularity','imdb_score' """ # To create movies bulky using file by pandas if 'upload_file' in request.data: df = pd.read_json(request.FILES['upload_file']) df.rename(columns={"99popularity": "popularity"}, inplace=True) objs = [ Movie(name=e.name, director=e.director, genre=','.join(e.genre), popularity=e.popularity, imdb_score=e.imdb_score) for e in df.itertuples() ] self.model.objects.bulk_create(objs) return Response({'msg': 'Success'}, status=200) # For create movie data = QueryDict.dict(request.data) genre = data.get('genre', '') data['genre'] = ','.join(genre) if genre and isinstance( genre, list) else genre serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): """ To create the User URL Structure: /user/signup/ Required Fields: 'name', 'email', 'phone', 'password' """ data = QueryDict.dict(request.data) serializer = self.serializer_class(data=data) if serializer.is_valid(): new_user = serializer.save() new_user.set_password(new_user.password) new_user.save() payload = jwt_payload_handler(new_user) context = { 'message': 'User created', 'token': jwt_encode_handler(payload), 'user_detail': { 'name': new_user.name, } } return Response(context) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def employee_create(request): user = request.session['obj'] hr = Employee.objects.filter(active_flag=True, id=user, role='hr') if hr: if request.POST: data = QueryDict.dict(request.POST) today = date.today() d1 = today.strftime("%y") data['date_of_joining'] = date.today() form = EmployeeCreateform(data=data) if form.is_valid(): form_obj = form.save() print(form_obj, 'pppppppppp', type(form_obj)) password = data.pop('password') form_obj.set_password(password) form_obj.save() print('sdfghcvb') emp = Employee.objects.get(pk=form_obj.id) print(d1, type(d1)) emp.employee_id = 'APPY' + '/' + d1 + '/' + str(emp.id) emp.save() else: return JsonResponse(form.errors) template = 'signup.html' form = EmployeeDisplayform() return render(request, template, {'form': form}) else: return HttpResponse({"no permission"})
def start_flutterwave_payment(request): success = False if request.method == "POST": entity_first_name = None entity_last_name = None entity_account_number = None entity_card6 = None entity_card_last4 = None try: payload_qdict = QueryDict(request.body) payload = payload_qdict.dict() if not (payload["flwRef"] == "N/A"): return end_flutterwave_payment(request) success = payment_funcs.process_flutterwave_start_mpesa_transaction( payload) except ValueError as e: print e raise Http404 except Exception as e: print e return HttpResponseServerError(e.message) return JsonResponse({"success": success})
def get_initial(self): initial = {'created_by': self.request.user.staff} qd = QueryDict(self.request.GET.urlencode()) if qd: initial.update(qd.dict()) else: # not model nor model.pk then raise 404 raise Http404 return initial
def create(self, request, *args, **kwargs): data = QueryDict.dict(request.data) comment_user = data.get("User") user = User.objects.get(username=comment_user) data["User"] = user.id serializer = PhotoCommentDeserializer(data=data) serializer.is_valid(raise_exception=False) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def qualificationcreate(request): if request.POST: data = QueryDict.dict(request.POST) user = request.session['obj'] emp = Employee.objects.get(active_flag=True, employee_id=user) data['user'] = user print(data) form = Qualificationcreateform(data=data) if form.is_valid(): form.save() return JsonResponse({'message': 'submitted'}) return JsonResponse(form.errors) form = QualificationDisplayform() return render(request, 'add_qualification.html', {'form': form})
def test_querydict_multiple(self): post = QueryDict('field=val1&field=val2') # simple __get_item__ returns last value self.assertEqual(post['field'], 'val2') # to get all values one have to use getlist self.assertEqual(post.getlist('field'), ['val1', 'val2']) # equals takes into account multiple values self.assertDictEqual(post, {'field': ['val1', 'val2']}) # but QueryDict.dict() don't (it just return the last value) self.assertDictEqual(post.dict(), {'field': 'val2'})
def familydetailscreate(request): if request.POST: data = QueryDict.dict(request.POST) user = request.session['obj'] emp = Employee.objects.get(active_flag=True, employee_id=user) data['user'] = emp.id print(data['user']) form = FamilydetailsCreateForm(data=data) if form.is_valid(): print(form) form.save() return JsonResponse({'message': 'submitted'}) return JsonResponse(form.errors) form = FamilydetailsDisplayForm() return render(request, 'add_familydetails.html', {'form': form})
def resignationcreate(request): if request.POST: data = QueryDict.dict(request.POST) user = request.session['obj'] emp = Employee.objects.get(active_flag=True, employee_id=user) data['user'] = emp.id data['submitted_on'] = date.today() form = ResignationCreateForm(data=data) if form.is_valid(): form.save() return JsonResponse({'message': 'submitted'}) return JsonResponse(form.errors) form = ResignationDisplayForm() return render(request, 'resignation.html', {'form': form})
def updatepfdetails(request, pk): obj = Employee.objects.get(pk=pk) print(obj.employee_id, 'pf') if request.POST: data = QueryDict.dict(request.POST) user = request.session['obj'] # emp = Employee.objects.get(active_flag=True, employee_id=user) data['user'] = obj.employee_id # print(data['user']) form = PFdetailsform(data=data) if form.is_valid(): print(form) form.save() return JsonResponse({'message': 'submitted'}) return JsonResponse(form.errors) form = PFdisplayform() return render(request, 'add_pf_details.html', {'form': form})
def updatebankdetails(request, pk): obj = Employee.objects.get(pk=pk) print(obj, 'asdad') if request.POST: data = QueryDict.dict(request.POST) # user = request.session['obj'] # emp = Employee.objects.get(active_flag=True, employee_id=obj.employee_id) # print(emp.employee_id) data['user'] = obj.id print(data) form = Bankdetailsform(data=data) if form.is_valid(): form.save() return HttpResponse({'submitted'}) return JsonResponse(form.errors) form = BankDisplayform() return render(request, 'add_bank_details.html', {'form': form})
def update(self, request, pk): """ To update the particular movie URL Structure: /movie/1/ Required Fields: 'id', 'name', 'director', 'genre', 'popularity','imdb_score' """ queryset = get_object_or_404(self.model, id=pk) data = QueryDict.dict(request.data) genre = data.get('genre', '') data['genre'] = ','.join(genre) if genre and isinstance( genre, list) else genre serializer = self.serializer_class(queryset, data=data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400)
def post(self, request): page_query = QueryDict(request.POST.get('next_page', ''), mutable=True) self.kwargs.update(page_query.dict()) self.object_list = self.get_queryset() context = self.get_context_data() html = render_to_string('catalog/products.html', context) if context['page_obj'].has_next(): page_number = context['page_obj'].next_page_number() page_query['page'] = page_number next_page = urllib.parse.unquote(page_query.urlencode()) else: page_number = None next_page = None return HttpResponse( json.dumps({ 'products': html, 'next_page': next_page, 'page_number': page_number }))
def post(self, request, *args, **kwargs): from django.http.request import QueryDict form_class = self.get_form_class() # Recibe la peticion enviada por POST # y actualiza agregando los campos por defecto basados en la vista data = QueryDict.dict(request.POST) data.update(**self.get_default_fields()) qdict = QueryDict('', mutable=True) qdict.update(data) form = form_class(qdict) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
def end_flutterwave_payment(request): response = None if request.method == "POST": payload = None try: payload_qdict = QueryDict(request.body) payload = payload_qdict.dict() print payload response = payment_funcs.process_flutterwave_end_mpesa_transaction( payload) except ValueError as e: print e raise Http404 except Exception as e: print e return HttpResponseServerError(e.message) if response is None: response = {"success": False} return JsonResponse(response)
def create(self, request, *args, **kwargs): """ To create the movie booking URL Structure: /movie/book/ Required Fields: 'user', 'show', 'seat_class', 'seat_number', 'no_of_tickets' """ data = QueryDict.dict(request.data) data['user'] = request.user.pk serializer = self.serializer_class(data=data) if serializer.is_valid(): obj = serializer.save() obj.service_fee = obj.no_of_tickets * 30 obj.total_cost = obj.service_fee + (obj.no_of_tickets * obj.seat_class.cost_per_ticket) obj.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): data = QueryDict.dict(request.data) print("\n\nREQUEST DATA" + "=" * 60) print(data) print("REQUEST DATA" + "=" * 60) print('\n\n') comment_user = data.get("User") print("\n\nCOMMENT USER" + "=" * 60) print(comment_user) print("COMMENT USER" + "=" * 60) print('\n\n') user = User.objects.get(username=comment_user) data["User"] = user.id serializer = GalleryCommentDeserializer(data=data) serializer.is_valid(raise_exception=False) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def save_shipment_details_to_db(shipment_data, seller_profile, access_token): logger.debug('shipment data', shipment_data) logger.debug('seller profile', seller_profile) logger.debug('Access token', access_token) for each_shipment in shipment_data['shipments']: shipmentId = str(each_shipment['shipmentId']) url = "https://api.bol.com/retailer/shipments/" + str(shipmentId) payload = {} headers = { 'Content-Type': 'application/json', 'Accept': 'application/vnd.retailer.v3+json', 'Authorization': 'Bearer ' + access_token } shipment_details_response = shipment_details_api(headers, url, payload) res_data = shipment_details_response.json() if shipment_details_response.status_code == 200: # save in shipping details try: shipping_details = ShippingDetails() shipping_details.seller_profile_id = seller_profile shipping_details.shipmentId = res_data['shipmentId'] shipping_details.shipmentDate = res_data['shipmentDate'] try: shipping_details.shipmentReference = res_data[ 'shipmentReference'] except: shipping_details.shipmentReference = "" shipping_details.pickUpPoint = res_data['pickUpPoint'] shipping_details.save() logger.debug('Shipping Details saved successfully') if res_data['transport']: transport_details_dict = QueryDict.dict( res_data['transport']) transport_serializer = TransportDetailsCreateSerializer( data=transport_details_dict) if transport_serializer.is_valid(): transport_serializer.save() shipping_details.transportDetails_id = transport_serializer.data[ 'id'] shipping_details.save() logger.debug( 'Transport details saved successfully in shipping details' ) if res_data['customerDetails']: customer_details_dict = QueryDict.dict( res_data['customerDetails']) customer_serializer = CustomerDetailsCreateSerializer( data=customer_details_dict) if customer_serializer.is_valid(): customer_serializer.save() shipping_details.customerDetails_id = customer_serializer.data[ 'id'] shipping_details.save() logger.debug( 'Customers details saved successfully in shipping details' ) if res_data["shipmentItems"]: for each_order in res_data["shipmentItems"]: order_details_dict = QueryDict.dict(each_order) order_serializer = OrderDetailsCreateSerializer( data=order_details_dict) if order_serializer.is_valid(): order_serializer.save() shipping_details.orderDetails.add( order_serializer.data['id']) shipping_details.save() try: if res_data['billingDetails']: billing_details_dict = QueryDict.dict( res_data['billingDetails']) billing_serializer = BillingDetailsCreateSerializer( data=billing_details_dict) if billing_serializer.is_valid(): billing_serializer.save() shipping_details.billingDetails_id = billing_serializer.data[ 'id'] shipping_details.save() logger.debug( 'Billing details saved successfully in shipping details' ) except: pass except: logger.debug('Shipping ID already Exists') elif shipment_details_response.status_code == 401 and res_data[ 'title'] == 'Expired JWT': access_token = get_new_access_token(seller_profile) return
def to_representation(self, instance): ret = super(LayerSerializer, self).to_representation(instance) qgs_maplayer = self.qgs_project.mapLayers()[instance.qgs_layer_id] group = instance.project.group # add attributes/fields ret['fields'] = self.get_attributes(instance) # add infoformat and infourl ret['infoformat'] = '' ret['infourl'] = '' lidname = instance.qgs_layer_id if instance.project.wms_use_layer_ids else instance.name # add bbox if instance.geometrytype != QGIS_LAYER_TYPE_NO_GEOM: if instance.extent: ret['bbox'] = instance.extent_rect else: # get from QgsMapLayer instance extent = qgs_maplayer.extent() ret['bbox'] = {} ret['bbox']['minx'] = extent.xMinimum() ret['bbox']['miny'] = extent.yMinimum() ret['bbox']['maxx'] = extent.xMaximum() ret['bbox']['maxy'] = extent.yMaximum() # add capabilities ret['capabilities'] = self.get_capabilities(qgs_maplayer) # add styles # FIXME: restore in the future for styles map management #ret['styles'] = self.qgis_projectsettings_wms.layers[lidname]['styles'] ret['source'] = {'type': instance.layer_type} # add options for wms layer if instance.layer_type in [ Layer.TYPES.wms, Layer.TYPES.arcgismapserver ]: if instance.layer_type == Layer.TYPES.wms: datasourceWMS = QueryDict(instance.datasource) else: datasourceWMS = datasourcearcgis2dict(instance.datasource) if ('username' not in ret['source'] or 'password' not in ret['source'] ) and 'type=xyz' not in instance.datasource: ret['source'].update(datasourceWMS.dict( ) if isinstance(datasourceWMS, QueryDict) else datasourceWMS) ret['source']['external'] = instance.external # add proj4 try: ret['proj4'] = G3WSpatialRefSys.objects.get( srid=ret['crs']).proj4text except: ret['proj4'] = None # add metadata #ret['metadata'] = self.qgis_projectsettings_wms.layers[lidname]['metadata'] ret['metadata'] = self.get_metadata(instance, qgs_maplayer) # eval editor_form_structure if ret['editor_form_structure']: ret['editor_form_structure'] = eval(instance.editor_form_structure) return ret