def api_get_preferences_page(request): forms = apps.get_app_config('nutrition_helper').forms forms = {key: forms[key] for key in ['phys-params-PAL-goal', 'food-preferences', 'energy', 'nutrients']} user = request.user.id user_params = UserParams.objects.filter(user=user) user_preferences = UserPreferences.objects.filter(user=user) user_requirements = UserRequirements.objects.filter(user=user) response = forms status = [] if user_params: status.append('phys-params-PAL-goal') params_serializer = MainUserParamsSerializer(user_params[0]) params = params_serializer.data params_form = [{**field, 'initialValue': params[field['name']]} for field in forms['phys-params-PAL-goal']] response['phys-params-PAL-goal'] = params_form if user_preferences: status.append('food-preferences') prefs_serializer = UserPreferencesSerializer(user_preferences[0]) prefs = prefs_serializer.data prefs_form = [{**field, 'initialValue': prefs[field['name']]} for field in forms['food-preferences']] response['food-preferences'] = prefs_form if user_requirements: status.extend(['energy', 'nutrients']) reqs_serializer = UserRequirementsSerializer(user_requirements[0]) reqs = reqs_serializer.data energy = [{**field, 'value': reqs[field['name']]} for field in forms['energy']] nutrients = [{**field, 'value': reqs[field['name']]} for field in forms['nutrients']] response['energy'] = energy response['nutrients'] = nutrients return Response({'data': response, 'status': status})
def UserUpdateStatus(data): """ :param data: Hash Code of the Query. :return: contributions of the user on updating Query Filter commit status. """ result = [] data['query'] = get_object_or_404(Query, hash_code=data['query']) status = data['query'].queryfilter.status p_open, g_open = -1, -1 if status is not None and status != "": status = status.split(",") if "p-open" in status or "g-open" in status: try: status.remove("p-open") p_open = 0 except ValueError: pass try: status.remove("g-open") g_open = 0 except ValueError: pass status.append("open") status = '|'.join(status) commits = ListCommit.objects.filter( Q(query=data['query']), Q(status__iregex="(" + status + ")")) else: commits = ListCommit.objects.all() for i in commits: if i.status.lower( ) == "open" and i.platform == "Phabricator" and p_open == -1: continue if i.status.lower( ) == "open" and i.platform == "Gerrit" and g_open == -1: continue obj = { "time": i.created_on, "status": i.status, "owned": i.owned, "assigned": i.assigned } if i.platform == 'Phabricator': obj['phabricator'] = True else: obj['gerrit'] = True result.append(obj) return Response({"result": result})
def get(self, request): status = [] for orderstatus in StatusModel.objects.all(): status.append({ "orderNumber": orderstatus.order.orderNumber, "salesPerson": orderstatus.order.salesPerson, "description": orderstatus.order.description, "orderDate": str(orderstatus.order.orderDate), "company": str(orderstatus.order.company), "shipmentAddress": orderstatus.order.shipmentAddress, "status": orderstatus.status, }) return JsonResponse(status, safe=False)
def upload_solutions_with_points(self, request, pk=None): if 'file' not in request.data: raise exceptions.ParseError(detail='No file attached') zfile = request.data['file'] if not zipfile.is_zipfile(zfile): raise exceptions.ParseError( detail='Attached file is not a zip file') zfile = zipfile.ZipFile(zfile) if zfile.testzip(): raise exceptions.ParseError(detail='Zip file is corrupted') pdf_files = [name for name in zfile.namelist() if name.endswith('.pdf')] status = [] for filename in pdf_files: try: parts = filename.rstrip('.pdf').split('-') score = int(parts[0]) problem_pk = int(parts[-2]) registration_pk = int(parts[-1]) event_reg = EventRegistration.objects.get(pk=registration_pk) solution = Solution.objects.get(semester_registration=event_reg, problem=problem_pk) except (IndexError, ValueError, AssertionError): status.append({ 'filename': filename, 'status': 'Cannot parse file' }) continue except EventRegistration.DoesNotExist: status.append({ 'filename': filename, 'status': f'User registration with id {registration_pk} does not exist' }) continue except Solution.DoesNotExist: status.append({ 'filename': filename, 'status': f'Solution with registration id {registration_pk} and problem id {problem_pk} does not exist' }) continue extracted_path = zfile.extract(filename, path='/tmp') new_path = os.path.join( settings.MEDIA_ROOT, 'solutions', solution.get_corrected_solution_file_name()) file_move_safe(extracted_path, new_path, allow_overwrite=True) solution.score = score solution.corrected_solution = solution.get_corrected_solution_file_name() solution.save() status.append({ 'filename': filename, 'status': f'OK - points: {score}' }) return Response(json.dumps(status))
def prj_data(request, what): model = globals()[what] pp = model._meta.related_objects[0].name #d._meta.get_all_related_objects()[0].name #print(what) #l=what.objects.all() d = model.objects.all() p = serializers.serialize('json', d) c = [] #sets=str(re.search('Workflow.(.*?)>',str(pp)).group(1))+'_set' sets = (str(pp) + '_set') if (what == 'Department'): for i in d: l = i.serializable_value(sets).values() c.append(l.count()) js = {'label': json.loads(p), 'count': c} else: s_m = globals()[pp.capitalize()] option = [i[0] for i in s_m.objects.all()[0].choices] status = [] for i in d: l = i.serializable_value(sets).values() c.append(l.count()) #[ i['status'] for i in range(l)] temp = [] for j in option: cn = [k['status'] for k in l] #cn.count(j) temp.append(cn.count(j)) status.append(temp) js = { 'label': json.loads(p), 'count': c, 'option': option, 'status': status } return JsonResponse(js)
def post(self, request, format=None): '''print(request.stream) adda=request.data['data_to_add'] print(type(request.data),type(adda),adda)''' if request.data['req_method'] == 'ADD': # convert str from elementui to json add_data = json.loads(request.data['data_to_add']) #serializer = Ref_Price_tSerializer(data=add_data, many=True) print(add_data,add_data['0']) add_one = json.loads(add_data['0']) added_num = 0 status = [] for key, data in add_data.items(): serializer = Ref_Price_tSerializer(data=json.loads(data)) if serializer.is_valid(): serializer.save() status.append( serializer.data['kind']+' added successfully') added_num = added_num+1 else: status.append( 'add '+serializer.data['kind'] + 'failed, error message: '+str(serializer.errors)) if added_num == 0 and add_one['line_price_fk']:#当没有一个挡位新增成功的时候,删除新增线路,确保每个新增的线路至少有一个挡位 line = Line_Price_t.objects.get(pk=serializer.data['local_agency_fk']) line.delete() added_data = {} if added_num == 1: ref_prices = Ref_Price_t.objects.filter( line_price_fk__id=add_one['line_price_fk'],kind=add_one['kind']) serializer = Ref_Price_tSerializer(ref_prices, many=True) return Response({'added_num': added_num, 'failed_num': len(add_data)-added_num, 'status': status,'added_data':serializer.data}) # get refprice by line_price_pk and local_agency_fk if request.data['req_method'] == 'GET': try: refP = Ref_Price_t.objects.filter(local_agency_fk=request.data['local_agency_fk']).filter( line_price_fk__id=request.data['line_price_fk']) except KeyError: return Response({'status_flag': False, 'status_string': 'key error'}, status=200) serializer = Ref_Price_tSerializer(refP, many=True) return Response({'result': serializer.data, 'item_num': len(refP), 'status_flag': True, 'status_string': 'Successfully get {0} ref_price item'.format(len(refP))}) if request.data['req_method'] == 'DELETE': try: refP = Ref_Price_t.objects.get(pk=request.data['pk']) except Ref_Price_t.DoesNotExist: return JsonResponse({'result': '', 'status_flag': False, 'status_string': 'Item did not exist', 'result_count': 0}) refP.delete() return Response({'status_flag': True, 'status_string': 'Successfully deleted !'}, status=200) if request.data['req_method'] == 'UPDATE': try: refP = Ref_Price_t.objects.get(pk=request.data['pk']) except Ref_Price_t.DoesNotExist: return JsonResponse({'result': '', 'status_flag': False, 'status_string': 'Item did not exist', 'result_count': 0}) serializer = Ref_Price_tSerializer( refP, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response({ 'status_flag': True, 'status_string': 'Update Success', 'result_count': 1}) return JsonResponse(serializer.errors, status=400)