def _format_json_list(self, obj, options): if (len(obj) > 0): result = [] for occ in obj: df = DateFormat(occ.created_at) new_date = df.format('m/d/Y H:i:s') o = { 'is_owner': is_owner(occ.id, options['request_user_id']), 'id': occ.id, 'user_id': occ.user_id, 'created_at': str(new_date), 'coordinate': occ.coordinate, 'category_id': occ.category_id, 'category_name': occ.category.name, 'title': occ.title, 'description': occ.description, 'validated': occ.validated, 'vote_counter': occ.vote_counter } result.append(o) return simplejson.dumps(result) else: return simplejson.dumps({'Success': False})
def get_occurrence(request, ident, user): result = {} result["success"] = False path = settings.CDN_URL + "/static/" occ = Occurrences.objects.get(id=int(ident)) df = DateFormat(occ.created_at) new_date = df.format('m/d/Y H:i:s') result["occurrence"] = {'id_occ': occ.id, 'user_id': occ.user_id, 'created_at': str(new_date), 'coordinate': occ.coordinate, 'category_id': occ.category_id, 'category_name': occ.category.name, 'title': occ.title, 'description': occ.description, 'vote_counter': occ.vote_counter} occ_photos = occ.photos_set.all() result["occurrence"]["photos"] = [] userObj = User.objects.get(id=int(user)) result["occurrence"]["is_following"] = is_following(occ, userObj) for photo in occ_photos: result["occurrence"]["photos"].append( {"path_small": path + photo.path_small, "path_big": path + photo.path_big, "path_medium": path + photo.path_medium}) result["success"] = True return HttpResponse(simplejson.dumps(result), content_type="json")
def recently_read(**kwargs): """ return html containing data from the recently read list Specify an argument n=[int] to determine how many entries are rendered in the list. """ num_entries = int(kwargs['n']) if 'n' in kwargs else lib.NUM_READ_LIST read_list = ReadingListItem.objects.filter(wishlist=False).order_by('-date_published')[:num_entries] list_html = format_html("<h3>Recently Read</h3><div class=\"book-list\">") for book in read_list: list_html += format_html("<div class='book-book-result book-book-result-hover group'>") list_html += format_html("<img src='{}' class='left'>", book.cover) list_html += format_html("<p class='title'>{}</p>", book.title) list_html += format_html("<p class='author'>{}</p>", book.author) list_html += format_html("<p class='description'>{}</p>", book.description) dt = DateFormat(book.date_published) list_html += format_html("<p class='date'>Added on {}</p>", dt.format("F j, Y g:i A")) if book.favorite: list_html += format_html("<span class='favorite' title='Cory\'s Favorites'>★</span>") list_html += format_html("<a class='overlay' href='{}' target='_blank'></a></div>", book.link) if len(read_list) == 0: list_html += format_html("<p class='empty'>Cory hasn't read any books yet!</p>") list_html += format_html("<p class='empty'><a href='{}'>(See More)</a></p></div>", reverse('books')) return list_html
def test_list_measurement(admin_client, live_server, # pylint: disable=R0914 webdriver): selenium = webdriver() create_correct_sample_data() create_characteristic_values() try: selenium.get(live_server + '/measurement/') login_as_admin(selenium) title = selenium.find_element_by_css_selector('#page-wrapper h1').text assert title == 'List of measurements' table_rows = selenium.find_elements_by_class_name('clickable-row') assert len(table_rows) == 19 all_meas = Measurement.objects.all() header = selenium.find_elements_by_css_selector('#page-wrapper th') assert len(header) == 6 for index, field_name in enumerate(['date', 'order', 'order_items', 'examiner', 'meas_item', 'measurement_tag']): field = Measurement._meta.get_field(field_name) # pylint: disable=W0212 assert header[index].text == field.verbose_name for index, row in enumerate(table_rows): url = '/measurement/{}/'.format(all_meas[index].pk) assert row.get_attribute('data-href') == url columns = row.find_elements_by_css_selector('#page-wrapper td') assert len(columns) == 6 date = DateFormat(all_meas[index].date) assert columns[0].text == date.format(settings.DATETIME_FORMAT) assert columns[1].text == str(all_meas[index].order).strip() items = all_meas[index].order_items.all() assert columns[2].text == ';'.join([str(item) for item in items]) assert columns[3].text == all_meas[index].examiner.username assert columns[4].text == str(all_meas[index].meas_item) assert columns[5].text == str(all_meas[index].measurement_tag) finally: selenium.quit()
def places(request): context_dict = {} if request.method == 'POST': from_station = request.POST.get('from_station') to_station = request.POST.get('to_station') date = request.POST.get('departure_date') time = request.POST.get('departure_time') train_number = request.POST.get('train_number') departure_date = datetime.strptime(date, "%Y-%m-%d") client = Client(api_usernumber = conf.USER_NUMBER, api_passmd5 = conf.USER_PASSMD5, id_terminal = conf.ID_TERMINAL, id_service = conf.ID_SERVICE, request_url = conf.API_URL) df = DateFormat(departure_date) places = client.get_train_places(from_station, to_station, df.format('d.m.Y'), time, train_number) data = json.dumps(places, ensure_ascii=False) response_dict = json.loads(data) if 'status' in response_dict: context_dict['error'] = response_dict['message'] else: context_dict = place_handler(response_dict) context_dict['data'] = data context_dict['from_station'] = Station.objects.get(code=from_station) context_dict['to_station'] = Station.objects.get(code=to_station) context_dict['departure_date'] = date context_dict['departure_time'] = time context_dict['train_number'] = train_number context_dict['stations'] = Station.objects.all() return render(request, 'search/places.html', context_dict)
def date_as_block_filter(value): df = DateFormat(value) result = '''<{0} class="day">{1}</{0}> <{0} class="month">{2}</{0}> <{0} class="year">{3}</{0}>'''.format( 'span', df.format('d'), df.format('M'), df.format('Y')) return mark_safe(result)
def get_value(self, value): if isinstance(value, date): date_format = DateFormat(value) return date_format.format("d/m/y").capitalize() elif isinstance(value, datetime): date_format = DateFormat(value) return date_format.format("d/m/y H:M").capitalize() return value
def get_initial(self): self.year = int(self.kwargs["year"]) self.month = int(self.kwargs["month"]) self.day = int(self.kwargs["day"]) dt = date(self.year, self.month, self.day) df = DateFormat(dt) return {'date': date(self.year, self.month, self.day), 'title': ("%s -" % df.format('F jS')), 'user':self.request.user.username}
def occurrences(request): user = User.objects.get(id=request.user.id) occurrences_objects = Occurrences.objects.filter( user=user, bullshit=0).order_by('created_at') forcing_objects = OccurrencesReforce.objects.filter(user=user) result = [] # query for own occurrences if (len(occurrences_objects) > 0): for occ in occurrences_objects: df = DateFormat(occ.created_at) new_date = df.format('m/d/Y H:i:s') o = {'is_owner': 1, 'id': occ.id, 'user_id': occ.user_id, 'user_name': user.username, 'created_at': str(new_date), 'coordinate': occ.coordinate, 'category_id': occ.category_id, 'forced': 0, 'category_name': occ.category.name, 'title': occ.title, 'description': occ.description, 'validated': occ.validated, 'vote_counter': occ.vote_counter} result.append(o) # query for occurrences user follows if(forcing_objects.exists()): for forcing in forcing_objects: occ = forcing.occurrence df = DateFormat(occ.created_at) new_date = df.format('m/d/Y H:i:s') perm = has_write_permission(occ.id, request.user.id) o = {'permission': perm, 'is_owner': 0, 'id': occ.id, 'user_id': occ.user_id, 'user_name': occ.user.username, 'created_at': str(new_date), 'coordinate': occ.coordinate, 'category_id': occ.category_id, 'forced': 1, 'category_name': occ.category.name, 'title': occ.title, 'description': occ.description, 'validated': occ.validated, 'vote_counter': occ.vote_counter} result.append(o) return HttpResponse(simplejson.dumps(result), content_type="json")
def server_time(request): """ AJAX call to get the current server time. """ if request.is_ajax(): df = DateFormat(datetime.now()) payload = df.format("F jS Y @ h:iA") else: payload = "Sorry, this URL is for AJAX calls only." return HttpResponse(payload, mimetype="text/plain")
def serialize_for_ajax(self): """ Serializes the time, puzzle, team, and status fields for ajax transmission """ message = dict() df = DateFormat(self.submission_time.astimezone(time_zone)) message['time_str'] = df.format("h:i a") message['puzzle'] = self.puzzle.serialize_for_ajax() message['team_pk'] = self.team.pk message['status_type'] = "submission" return message
def rfc3339(value): from django.utils.dateformat import DateFormat if not value: return u'' try: df = DateFormat(value) offset = (lambda seconds: u"%+03d:%02d" % (seconds // 3600, (seconds // 60) % 60))(df.Z()) return df.format("Y-m-d\TH:i:s") + offset except AttributeError: return ''
def sales_items_paginate(request): page = int(request.GET.get('page')) list_sz = request.GET.get('size') p2_sz = request.GET.get('psize') select_sz = request.GET.get('select_size') date = request.GET.get('gid') sales = Sales.objects.all().order_by('-id') today_formart = DateFormat(datetime.date.today()) today = today_formart.format('Y-m-d') ts = Sales.objects.filter(created__icontains=today) tsum = ts.aggregate(Sum('total_net')) total_sales = Sales.objects.aggregate(Sum('total_net')) total_tax = Sales.objects.aggregate(Sum('total_tax')) try: last_sale = Sales.objects.latest('id') last_date_of_sales = DateFormat(last_sale.created).format('Y-m-d') all_sales = Sales.objects.filter(created__contains=last_date_of_sales) total_sales_amount = all_sales.aggregate(Sum('total_net')) items = SoldItem.objects.values('product_name', 'product_category', 'sku', 'quantity', 'unit_cost') \ .annotate(Count('sku')) \ .annotate(Sum('total_cost')) \ .annotate(Sum('unit_cost')) \ .annotate(Sum('quantity')).order_by('product_name') total_items = [] for t in items: product = ProductVariant.objects.get(sku=t['sku']) try: itemPrice = product.get_cost_price().gross * t['quantity'] retailPrice = product.get_cost_price().gross except ValueError, e: itemPrice = product.get_cost_price() * t['quantity'] retailPrice = product.get_cost_price() except: itemPrice = 0 retailPrice = 0 unitSalesCost = t['unit_cost'] totalSalesCost = t['total_cost__sum'] try: grossProfit = unitSalesCost - itemPrice unitMargin = unitSalesCost - retailPrice salesMargin = totalSalesCost - (itemPrice) totalCost = retailPrice * t['quantity'] except: grossProfit = 0 unitMargin = 0 salesMargin = 0 totalCost = 0 t['unitMargin'] = unitMargin t['salesMargin'] = salesMargin t['retailPrice'] = retailPrice t['totalCost'] = totalCost total_items.append(t)
def by_date(self, request, year, month=None, day=None, *args, **kwargs): self.posts = self.queryset.filter(first_published_at__year=year) self.filter_type = _('date') self.filter_term = year if month: self.posts = self.posts.filter(date__month=month) df = DateFormat(date(int(year), int(month), 1)) self.filter_term = df.format('F Y') if day: self.posts = self.posts.filter(date__day=day) self.filter_term = date_format(date(int(year), int(month), int(day))) return Page.serve(self, request, *args, **kwargs)
def send_chat_message(message): redis_publisher = RedisPublisher(facility='chat_message', users=[settings.ADMIN_ACCT, message.team.login_info.username]) packet = dict() packet['team_pk'] = message.team.pk packet['team_name'] = message.team.team_name packet['text'] = message.text packet['is_response'] = message.is_response df = DateFormat(message.time.astimezone(time_zone)) packet['time'] = df.format("h:i a") packet = RedisMessage(json.dumps(packet)) redis_publisher.publish_message(packet)
def format_story_link_date__long(date, now=None): if not now: now = datetime.datetime.utcnow() diff = now.date() - date.date() parsed_date = DateFormat(date) if diff.days == 0: return 'Today, ' + parsed_date.format('F jS ') + date.strftime('%I:%M%p').lstrip('0').lower() elif diff.days == 1: return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.','') elif date.date().timetuple()[7] == now.date().timetuple()[7]: return parsed_date.format('l, F jS g:ia').replace('.','') else: return parsed_date.format('l, F jS, Y g:ia').replace('.','')
def entries_by_date(self, request, year, month=None, day=None, *args, **kwargs): self.entries = self.get_entries().filter(date__year=year) self.search_type = _('date') self.search_term = year if month: self.entries = self.entries.filter(date__month=month) df = DateFormat(date(int(year), int(month), 1)) self.search_term = df.format('F Y') if day: self.entries = self.entries.filter(date__day=day) self.search_term = date_format(date(int(year), int(month), int(day))) return Page.serve(self, request, *args, **kwargs)
def send_new(request, author, body): dajax = Dajax() joke = Joke(author=author, body=body) joke.save() body = body.replace('\n', '<br />') date = joke.date df = DateFormat(date) function = 'set_new("{}", "{}", "{}", "{}");'.format(author, df.format(DATETIME_FORMAT), joke.pk, body) dajax.script(function) return dajax.json()
def format_story_link_date__long(date, now=None): if not now: now = datetime.datetime.utcnow() diff = now.date() - date.date() parsed_date = DateFormat(date) if diff.days == 0: return "Today, " + parsed_date.format("F jS ") + date.strftime("%I:%M%p").lstrip("0").lower() elif diff.days == 1: return "Yesterday, " + parsed_date.format("F jS g:ia").replace(".", "") elif date.date().timetuple()[7] == now.date().timetuple()[7]: return parsed_date.format("l, F jS g:ia").replace(".", "") else: return parsed_date.format("l, F jS, Y g:ia").replace(".", "")
def sales_paginate(request): page = int(request.GET.get('page')) list_sz = request.GET.get('size') p2_sz = request.GET.get('psize') select_sz = request.GET.get('select_size') date = request.GET.get('gid') sales = Sales.objects.all().order_by('-id') today_formart = DateFormat(datetime.date.today()) today = today_formart.format('Y-m-d') ts = Sales.objects.filter(created__icontains=today) tsum = ts.aggregate(Sum('total_net')) total_sales = Sales.objects.aggregate(Sum('total_net')) total_tax = Sales.objects.aggregate(Sum('total_tax')) if date: try: all_salesd = Sales.objects.filter(created__icontains=date).order_by('-id') that_date_sum = Sales.objects.filter(created__contains=date).aggregate(Sum('total_net')) sales = [] total_margin = [] for sale in all_salesd: costPrice = [] discounts = [] quantity = SoldItem.objects.filter(sales=sale).aggregate(c=Sum('quantity')) setattr(sale, 'quantity', quantity['c']) for i in SoldItem.objects.filter(sales=sale): product = ProductVariant.objects.get(sku=i.sku) try: quantity = product.get_cost_price().gross * i.quantity except ValueError, e: quantity = product.get_cost_price() * i.quantity except: quantity = 0 costPrice.append(quantity) discounts.append(i.discount) totalCostPrice = sum(costPrice) totalDiscounts = sum(discounts) setattr(sale, 'totalCostPrice', totalCostPrice) setattr(sale, 'totalDiscounts', totalDiscounts) try: grossProfit = sale.total_net - totalCostPrice margin = round(grossProfit - totalDiscounts, 2) except Exception as e: grossProfit = 0 margin = 0 setattr(sale, 'margin', margin) sales.append(sale) total_margin.append(margin)
def send_submission_update(submission): redis_publisher = RedisPublisher(facility='puzzle_submissions', users=[submission.team.login_info.username, settings.ADMIN_ACCT]) modelJSON = json.loads(serializers.serialize("json", [submission]))[0] message = modelJSON['fields'] message['response_text'] = escape(message['response_text']) message['puzzle'] = submission.puzzle.puzzle_id message['puzzle_name'] = submission.puzzle.puzzle_name message['team'] = submission.team.team_name message['pk'] = modelJSON['pk'] df = DateFormat(submission.submission_time.astimezone(time_zone)) message['time_str'] = df.format("h:i a") message = RedisMessage(json.dumps(message)) redis_publisher.publish_message(message)
def format_story_link_date__long(date, now=None): if not now: now = datetime.datetime.now() date = date.replace(tzinfo=None) midnight = midnight_today(now) parsed_date = DateFormat(date) if date >= midnight: return "Today, " + parsed_date.format("F jS ") + date.strftime("%I:%M%p").lstrip("0").lower() elif date >= midnight_yesterday(midnight): return "Yesterday, " + parsed_date.format("F jS g:ia").replace(".", "") elif date >= beginning_of_this_month(): return parsed_date.format("l, F jS g:ia").replace(".", "") else: return parsed_date.format("l, F jS, Y g:ia").replace(".", "")
def serialize_for_ajax(self): """ Serializes the puzzle, team, time, and status fields for ajax transmission """ message = dict() message['puzzle'] = self.puzzle.serialize_for_ajax() message['team_pk'] = self.team.pk try: # Will fail if there is more than one solve per team/puzzle pair # That should be impossible, but lets not crash because of it time = self.submission.submission_time df = DateFormat(time.astimezone(time_zone)) message['time_str'] = df.format("h:i a") except: message['time_str'] = "0:00 am" message['status_type'] = "solve" return message
def format_story_link_date__long(date, now=None): if not now: now = datetime.datetime.now() date = date.replace(tzinfo=None) midnight = midnight_today(now) parsed_date = DateFormat(date) if date >= midnight: return 'Today, ' + parsed_date.format('F jS ') + date.strftime('%I:%M%p').lstrip('0').lower() elif date >= midnight_yesterday(midnight): return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.','') elif date >= beginning_of_this_month(): return parsed_date.format('l, F jS g:ia').replace('.','') else: return parsed_date.format('l, F jS, Y g:ia').replace('.','')
def send_status_update(puzzle, team, status_type): # status_type should be either "solve" or "unlock" redis_publisher = RedisPublisher(facility='puzzle_status', users=[team.login_info.username, settings.ADMIN_ACCT]) message = dict() message['puzzle_id'] = puzzle.puzzle_id message['puzzle_num'] = puzzle.puzzle_number message['puzzle_name'] = puzzle.puzzle_name message['team_pk'] = team.pk message['status_type'] = status_type if(status_type == 'solve'): time = team.solve_set.filter(puzzle=puzzle)[0].submission.submission_time df = DateFormat(time.astimezone(time_zone)) message['time_str'] = df.format("h:i a") message = RedisMessage(json.dumps(message)) redis_publisher.publish_message(message)
def aggregate(self, as_dict=False): map(self.aggregate_review, self.reviews) # Format the date as "February 2, 2014" if 'date' in self.aggregate_values: df = DateFormat(self.aggregate_values['date']) self.aggregate_values['date'] = df.format('F j, Y') if 'prof_course' in self.aggregate_values: self.aggregate_values.pop('prof_course', None) self.aggregate_values['count'] = self.count if as_dict: return self.aggregate_values else: return json.dumps(self.aggregate_values)
def send_form(request, form): dajax = Dajax() form = ProductOneClickForm(deserialize_form(form)) dajax.remove_css_class('#loader2', 'hidden') if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dajax.remove_css_class('#loader2', 'hidden') # result = u'Отправляем сообщение' # dajax.assign('#status', 'value', result) phone = form.cleaned_data.get('phone') product_name = form.cleaned_data.get('product_name') date = datetime.now() dateFormat = DateFormat(date) dateFormat = dateFormat.format(get_format('DATE_FORMAT')) subject = u'Заявка в 1 клик %s' % dateFormat message = u'Дата: %s \n Телефон: %s \n Товар: %s' % (dateFormat, phone , product_name) send_mail(subject, message, '*****@*****.**', [ADMIN_EMAIL], fail_silently=False) order = OrderOneClick(phone=phone , product_name=product_name) order.save() # dajax.remove_css_class('#status', 'hidden') # result = u'Сообщение отправлено' # dajax.assign('#status', 'value', result) dajax.remove_css_class('#message_show', 'hidden') # dajax.script('closemodal()') # dajax.redirect('/', delay=2000) # dajax.code('$(".close").click()') else: dajax.remove_css_class('#my_form input', 'error') # dajax.remove_css_class('#status', 'hidden') # result = u'Введите данные' # dajax.assign('#status', 'value', result) for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') dajax.add_css_class('#loader2', 'hidden') return dajax.json()
def generar_listado_inscritos_priorizados(): #dubs = Dub.objects.filter(Q(estado=1) | Q(estado=2) )\ #.filter(dub_fecha_solicitud_inscripcion__lt="2016-01-01").count() dubs = Dub.objects.filter(barrio__isnull=True)\ .order_by("-estado")\ .all() #.filter(estado=estado_)\ #dub_fecha_solicitud_inscripcion book = xlwt.Workbook(encoding="utf-8") sheet1 = book.add_sheet("Sheet 1") f=1 for dub in dubs: print f, dub df = DateFormat(dub.dub_fecha_solicitud_inscripcion) sheet1.write(f, 0, f) sheet1.write(f, 1, int(dub.persona.per_doc_numero)) sheet1.write(f, 2, dub.persona.per_apellido1) sheet1.write(f, 3, dub.persona.per_apellido2) sheet1.write(f, 4, dub.persona.per_nombre1) sheet1.write(f, 5, dub.persona.per_nombre2) sheet1.write(f, 6, dub.persona.per_genero) sheet1.write(f, 7, dub.persona.edad) sheet1.write(f, 8, df.format('Y/m/d')) sheet1.write(f, 9, str(dub.estado)) sheet1.write(f, 10, dub.dub_telefono_fijo) sheet1.write(f, 11, dub.dub_telefono_movil) sheet1.write(f, 12, dub.dub_direccion) if dub.barrio: sheet1.write(f, 13, dub.barrio.__unicode__()) if dub.barrio.comuna: sheet1.write(f, 14, dub.barrio.comuna.__unicode__()) sheet1.write(f, 15, dub.dub_punto_cobro) sheet1.write(f, 16, dub.dub_valor_cobro) #sheet1.write(f, 10, dub.dub_posicion_priorizacion) f=f+1 filename = "/var/www/dubs_django/htdocs/media/listado_.xls" book.save(filename)
def diagram(request): data = [] rooms = Rooms.objects.all() try: if request.POST: roomsPOSTGraph = request.POST.get('r', False) roomsName = Rooms.objects.get(nameRoom=roomsPOSTGraph) date_start = request.POST.get('dateStart', False) date_end = request.POST.get('dateEnd', False) for s in Sensor.objects.all(): if roomsName == s.idRoom: measurement_graph = MeasurementData.objects.filter(idSensor=s.id, timestamp__gte=date_start, timestamp__lte=date_end) for m in measurement_graph: data.append(MeasurementClass(m.timestamp, m.temperature, m.humidity, m.idSensor, roomsName)) text = "----" first_data = date_start last_data = date_end else: text = "Wszystkie Pomiary" sensor = Sensor.objects.get(id=1) roomsName = sensor.idRoom data = MeasurementData.objects.filter(idSensor=1) df = DateFormat(data[0].timestamp) first_data = df.format('Y-m-d') df2 = DateFormat(data[len(data)-1].timestamp) last_data = df2.format('Y-m-d') except ObjectDoesNotExist: textproblem = "Prosze o wybranie czujnika." return render(request, 'diagram.html', {'problem': textproblem, 'rooms': rooms}) except ValidationError as e: textproblem = "Prosze o wybranie daty." return render(request, 'diagram.html', {'problem': textproblem, 'rooms': rooms}) return render_to_response('diagram.html', {'data': data, 'rooms': rooms, 'text': text, 'roomName': roomsName, 'firstData': first_data, 'lastData': last_data}, context_instance=RequestContext(request))
def info_session(request, session_type): try: STYPES[session_type] except: raise Http404, "Page not found" if request.method == 'POST': form = InfoSessionForm(session_type,request.POST) if form.is_valid(): cd = form.cleaned_data cd['session_type'] = session_type # fetch event event = Event.objects.using('livewhale').get(pk=cd['event']) cd['event'] = event # munge datetime lc = localtime(event.date_dt) df = DateFormat(lc) day = df.format('D') date = df.format('M d, Y') time = df.format('h:ia') datetime = '%s. %s at %s' % (day, date, time) cd['datetime'] = datetime # to recipients = settings.CONTINUING_EDUCATION_INFOSESSION_RECIPIENTS to = recipients[session_type] if settings.DEBUG: to = [settings.SERVER_MAIL,] subject = "OCS Information Session Request: " subject +="%s on %s" % (session_type, datetime) send_mail( request, to, subject, cd['email'], 'admissions/infosession.txt', cd, BCC, content='' ) return HttpResponseRedirect( reverse_lazy('info_session_success') ) else: form = InfoSessionForm(session_type) return render( request, 'admissions/infosession.html',{'form': form,} )
def get(self, request, accommodation_id): if not Accommodation.objects.filter(id=accommodation_id).exists(): return JsonResponse({"message": "PAGE_NOT_FOUND"}, status=404) accommodation = Accommodation.objects.select_related('user', 'category').prefetch_related('review_set').get(id=accommodation_id) review_avg = accommodation.review_set.aggregate( clean_avg = Coalesce(Avg('clean_rate'), 0), accuracy_avg = Coalesce(Avg('accuracy_rate'), 0), communication_avg = Coalesce(Avg('communication_rate'), 0), location_avg = Coalesce(Avg('location_rate'), 0), checkin_avg = Coalesce(Avg('checkin_rate'), 0), value_avg = Coalesce(Avg('value_rate'), 0), ) data = { 'id' : accommodation.id, 'title' : accommodation.title, 'address' : accommodation.address, 'lat' : accommodation.latitude, 'long' : accommodation.longitude, 'firstImg' : accommodation.image_set.first().image_url, 'img' : [image.image_url for image in accommodation.image_set.all()[1:]], 'description': accommodation.description, 'onedayPrice': accommodation.price, 'cleaningFee': accommodation.cleaning_fee, 'hostName' : accommodation.user.name, 'hostProfile': accommodation.user.profile_image, 'roomType' : { 'name' : accommodation.category.name, 'description': accommodation.category.description }, 'maxPeople' : accommodation.max_capacity, 'beds' : accommodation.number_of_bed, 'bedrooms' : accommodation.number_of_bedroom, 'bathrooms' : accommodation.number_of_bathroom, 'totalCount' : accommodation.review_set.count(), 'totalAvg' : round(mean(review_avg.values()), 2), 'grade' : [{ 'average' : round(each_average, 1), 'gradeValue': round(each_average * 100 / 5) } for each_average in review_avg.values()], 'comment' : [{ 'reviewid' : review.id, 'userName' : review.user.name, 'userProfile': review.user.profile_image, 'content' : review.content, 'createdAt' : DateFormat(review.created_at).format('Ym') } for review in accommodation.review_set.all()] } return JsonResponse(data, status=200)
def add(request): amount = Decimal(request.POST.get('amount')) try: try: lastEntry = PettyCash.objects.latest('id') pd = DateFormat(lastEntry.created).format('Y-m-d') td = DateFormat(datetime.datetime.today()).format('Y-m-d') if td == pd: lastEntry.added = lastEntry.added + amount lastEntry.closing = lastEntry.closing + amount lastEntry.save() balance = lastEntry.closing else: new_opening = lastEntry.closing new_balance = lastEntry.closing + amount new_petty_cash = PettyCash(opening=new_opening, added=amount, closing=new_balance) new_petty_cash.save() balance = new_petty_cash.closing user_trail(request.user.name, 'added KShs. '+ str(amount)+' to petty cash balance of KShs. '+ str(lastEntry.closing)+' current balance is KShs. '+str(lastEntry.closing + amount), 'update') info_logger.info( 'User: '******'added KShs. '+ str(amount)+' to petty cash balance of KShs. '+ str(lastEntry.closing)+' current balance is '+str(lastEntry.closing + amount), 'update') return HttpResponse(balance) except: new_petty_cash = PettyCash(opening=amount, added=0, closing=amount) new_petty_cash.save() balance = new_petty_cash.closing user_trail(request.user.name, 'added KShs. ' + str(amount) + ' to petty cash, current balance is KShs. ' + str(balance), 'update') info_logger.info( 'User: '******'added KShs. ' + str(amount) + ' to petty cash, current balance is ' + str(balance), 'update') return HttpResponse(balance) except Exception, e: error_logger.error(e) HttpResponse(e)
def get(self, request, format=None): df = DateFormat(datetime.now()) mins_ago = long(df.U()) - 500 #10 mins riders = {} cursor = connection.cursor() cursor.execute( """SELECT rider_id, speed, ST_X(coords), ST_Y(coords) FROM ( SELECT rider_id, speed, coords, RANK() OVER (PARTITION BY rider_id ORDER BY time DESC) as rank FROM location_update_location WHERE speed != 0)dt WHERE dt.rank <= 10""") for row in cursor.fetchall(): (rider_id, speed, lon, lat)=row if not riders.has_key(rider_id): riders[rider_id] = [] riders[rider_id].append((int(speed), lon, lat)) riders = riders.values() return Response( {'locations': riders}, status=status.HTTP_200_OK)
def now(format_string): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} """ from datetime import datetime from django.utils.dateformat import DateFormat return DateFormat(datetime.now()).format(self.format_string)
def file_upload_location(instance, filename): '''파일 업로드 기능''' from random import choice import string # string.ascii_letters : ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz #_base_dir = instance.mpboard_id.division _today = DateFormat(datetime.now()).format('Ymd') _uid = uuid.uuid4() _extension = filename.split('.')[-1] # 배열로 만들어 마지막 요소를 추출하여 파일확장자로 지정 _file_name = filename.split('.')[0] # 배열로 만들어 마지막 요소를 추출하여 파일확장자로 지정 #arr = [choice(string.ascii_letters) for _ in range(8)] #pid = ''.join(arr) # 8자리 임의의 문자를 만들어 파일명으로 지정 # file will be uploaded to MEDIA_ROOT/user_<id>/<random> #return 'mpboard/%s/%s/%s/%s_%s.%s' % ( _base_dir , _today , instance.mpboard_id.user_id , _file_name,_uid , _extension) # 예 : _base_dir/[날짜]/[mpboard_id]/uuid.png return 'mpboard/{ymd}/{name}_{uid}.{ext}'.format( ymd = _today , name = _file_name, uid = _uid , ext = _extension) # 예 : _base_dir/[날짜]/[mpboard_id]/uuid.png
def yearly_visits_data(self, year=None): """ :param year: :return: Total visits each month """ final_data = [] last_instance = self.get_queryset().latest('id') if not year: year = DateFormat(last_instance.created).format('Y') for month in range(1, 13): count = self.get_queryset().filter(created__year=year)\ .filter(created__month=month).count() final_data.append([str(year)+str(1)+str(month), count]) return final_data
def userbreg(request): userid = request.session['userid'] if tbpets.objects.filter(userid=userid): pets = tbpets.objects.filter(userid=userid) if request.method == "POST": mat = request.POST.get('matter') dogid = request.POST.get('arg1') boardingid = request.POST.get('boardingid') dt = datetime.now() df = DateFormat(dt) date = df.format('d-m-Y') sub = "BoardingRequest" status = "" seen = "" data1 = tbnoti.objects.create(sentid=userid, recid=boardingid, date=date, subject=sub, mater=mat, status=status, seend=seen, arg1=dogid) return HttpResponseRedirect(reverse('userapp:userboarding'))
def test_node_aliases(self): """ Test node save overridden function that produces aliases :return: None """ page_type = PageType.objects.create( name='test_aliases', description="Test aliases", url_pattern='test/[node:title]/[node:created:Y-m-d]/[node:id]') node = Node.objects.create(page_type=page_type, title="Test aliases node", user=self.node_rev_basic.node.user) alias = 'test/test-aliases-node/%s/%d' % (DateFormat( node.created).format('Y-m-d'), node.id) self.assertEqual(node.alias, alias)
def borrow(request, book_id, user_id): detailurl = request.build_absolute_uri( reverse('books:detail', args=[book_id])) book = Book.objects.get(pk=book_id) user = User.objects.get(pk=user_id) book.borrowed = True book.borrower = user book.status = 'o' book.save() date = DateFormat(datetime.now()).format(get_format('DATE_FORMAT')) new_borrowing = Borrowing(borrowing_date=date, book=book, borrower=user) new_borrowing.save() # return render(request, 'books/detail.html', {'detailurl': detailurl, 'book': book}) return HttpResponseRedirect('/')
def savePedido(request, anyway=None): #Validar si se debe guardar anyway #request.GET.get('anyway') if anyway == None: #Buscar si ya esta esa mesa con un pedido sin pagar idMaestroDetalle = buscarPedido( int((request.POST['mesa_p'], '0')[request.POST['mesa_p'] == ''])) if idMaestroDetalle: response_text = { 'code': '01' } #Ya existe un pedido para la mesa sin pagar return HttpResponse(json.dumps(response_text), content_type="application/json") idFactura = None if request.POST['idFactura'] != '': idFactura = int(request.POST['idFactura']) factura = VentaMaestro.objects.get(id=idFactura) else: factura = VentaMaestro() factura.cliente = User(id=(int(request.POST['idcliente_p']), 1)[request.POST['idcliente_p'] == '']) factura.vendedor = User(id=(int(request.POST['idvendedor_p']), 1)[request.POST['idvendedor_p'] == '']) factura.cajero = request.user #factura.valorPropina=int((request.POST['propina_p'],'0')[request.POST['propina_p']=='']) factura.mesa = int( (request.POST['mesa_p'], '0')[request.POST['mesa_p'] == '']) factura.save() df = DateFormat(factura.fechaVenta) response_text = { 'code': '00', 'nroFactura': factura.id, 'fechaVenta': df.format('d/M/Y'), 'horaVenta': df.format('h:i A') } return HttpResponse(json.dumps(response_text), content_type="application/json")
def due_credit_notifier(request): due_credits = Credit.objects.due_credits().filter(notified=False) for credit in due_credits: subject = 'OVERDUE CREDIT: ' + \ str(credit.invoice_number) + \ ' (' + str(DateFormat(credit.created).format('Y-m-d')) + \ ')' body = "Hi,<br>Customer:" + \ str(credit.customer.name) + \ '(' + str(credit.customer.mobile) + \ ')<br><b>Credit date:</b>' + str(DateFormat(credit.created).format('Y-m-d')) + \ '<br><b>Due Date:</b>' + str(DateFormat(credit.due_date).format('Y-m-d')) + \ '<br><b>Invoice Number:</b>' + str(credit.invoice_number) + \ '<br><b>Amount:</b>' + str(credit.total_net) custom_notification(request.user, body, subject) credit.notified = True credit.save() stocks = Stock.objects.get_low_stock(False) for stock in stocks: subject = ' Low Stock: ' + \ str(stock.variant.display_product()) + \ ' - ' + str(stock.variant.sku) + \ '' body = "Hi,<br>: Low Stock Notification<br>" + \ '<table class="table table-xxs"><thead><tr class="bg-primary">' + \ '<th>Name</th><th>SKU</th><th>Quantity</th><th>Threshold</th></tr></thead><tbody><tr>' + \ '<td>' + str(stock.variant.display_product()) + '</td>' + \ '<td>' + str(stock.variant.sku) + '</td>' + \ '<td>' + str(stock.quantity) + '</td>' + \ '<td>' + str(stock.low_stock_threshold) + '</td>' + \ '</tr></tbody>' custom_notification(request.user, body, subject) stock.notified = True stock.save() return HttpResponse(len(due_credits))
def get_today_special(request): if request.method == 'POST': try: data = JSONParser().parse(request) user_no = data['user_no'] # 오늘 날짜 구하기 today = str(DateFormat(datetime.now()).format('Ymd')) year, month, day = today[0:4], today[4:6], today[6:8] start_date = datetime.strptime(year + " " + month + " " + day, '%Y %m %d') end_date = datetime.strptime( year + " " + month + " " + day + " 23:59", '%Y %m %d %H:%M') # 하루 중 평균 별점이 높은 음식 5가지 구하기 today = Review.objects.filter( rev_date__range=[start_date, end_date]) if today.exists(): foods = today.distinct().values_list('food_no', flat=True) # 음식별 오늘의 평균 별점 구하기 review_star = np.array([]) for food_no in foods: food_review = today.filter(food_no=food_no) food_star = food_review.values_list('rev_star', flat=True) sum_star = sum(food_star) review_star = np.append(review_star, [sum_star / food_review.count()]) # 별점 높은 순으로 정렬 sorted_star = np.sort(review_star)[::-1] idx_sorted_cnt = np.argsort(-review_star) foods = np.array(foods)[idx_sorted_cnt] # 5가지 음식만 추출 if len(foods) > TODAY_FOOD_CNT: foods = foods[:TODAY_FOOD_CNT] sorted_star = sorted_star[:TODAY_FOOD_CNT] lang_code = User.objects.get(user_no=user_no).lang_no.lang_code response = get_foods_by_list(foods, lang_code) for i in range(len(response)): response[i]["today_avg_star"] = sorted_star[i] return JsonResponse(response, safe=False, status=200) # 정상 return JsonResponse(None, safe=False, status=201) # 하루동안 작성된 리뷰가 없는 경우 except KeyError: return JsonResponse({"message": "INVALID_KEY"}, status=400)
def get_update(request,last_post): last_post=int(last_post) posts=Post.objects.filter(pk__gt = last_post).order_by("-time") profiles=set() for post in posts: profiles.add(Profile.objects.get(user=post.profile.user)) postJson = serializers.serialize("json",posts) profileJson = serializers.serialize("json",profiles) timestamp={} for post in posts: df = DateFormat(localtime(post.time)) date=df.format(get_format('DATE_FORMAT')) time=df.format('f a') datetime=date+", "+time timestamp[post.id]=datetime last_post_id = Post.objects.latest('id').id # last_post_id=Post.objects.order_by('id')[0].id; context=json.dumps({"posts":postJson, "profile":profileJson, "time":timestamp, "last_post_id":last_post_id, }) return HttpResponse(context, content_type='application/json')
class Board(models.Model): b_no = models.AutoField(db_column='b_no', primary_key=True) b_title = models.CharField(db_column='b_title', max_length=255) b_note = models.CharField(db_column='b_note', max_length=4096) b_writer = models.CharField(db_column='b_writer', max_length=50) b_date = models.DateTimeField(db_column='b_date', default=DateFormat( datetime.now()).format('Ymd')), class Meta: managed = False db_table = 'board' def __str__(self): return "제목 : " + self.b_title + " 작성자 : " + self.b_writer
def boardInsert(request): if request.method == 'GET': return render(request, 'boardinsert.html') else: writer = request.POST.get("writer") title = request.POST.get("title") content = request.POST.get("content") Board(writer=writer, title=title, content=content, write_time=DateFormat(datetime.today()).format('Y-m-d H:i:s'), read_count=0).save() return HttpResponseRedirect('/board')
def to_detail_table(date) -> tuple: """ 详情页的详细消费信息 """ bill_id = get_sure_month_bill(date) bills = [] detail_data = bill_id.day_detail.all().order_by('date') for data in detail_data: bills.append({ 'date': DateFormat(data.date).c(), 'name': data.name or '', 'amount': data.amount or 0, 'note': data.note or '', 'type': data.type, }) return bills, columns
def __init__(self, *args, **kwargs): appointment = kwargs.pop('appointment') super(EditAppointmentForm_by_director, self).__init__(*args, **kwargs) self.fields['patientName'].initial = appointment.patientName self.fields['patientSurname'].initial = appointment.patientSurname self.fields['AMKA'].initial = appointment.AMKA self.fields['insuranceFund'].initial = appointment.insuranceFund self.fields['diseaseDetails'].initial = appointment.diseaseDetails self.fields['clinicid'].initial = appointment.clinicid self.fields['appointmentDate'].initial = DateFormat( datetime.strptime(appointment.strAppointmentDate, '%Y-%m-%d')).format('d/m/Y') self.fields['appointmentTime'].initial = re.sub( '\:00', '', appointment.strAppointmentTime) self.fields[ 'appointmentEmergency'].initial = appointment.appointmentEmergency
def search(request): """ 거래내역의 수집 결과를 조회합니다. - https://docs.popbill.com/easyfinbank/python/api#Search """ try: # 팝빌회원 사업자번호 CorpNum = "6630801510" UserID = "metis08" BankCode = "0004" AccountNumber = "45700101462642" # 시작일자, 날짜형식(yyyyMMdd) today = DateFormat(datetime.now()).format('Ymd') #today = datetime.date.today() SDate = "20200808" #today # 어제 날짜 구해서 넣어야 됨 (오늘 구하다가 에러나서 일단 넘아감, 밤 왜냐하면 11.59분에 결제하면 어제 결제확인 안될수 있음) EDate = today # 팝빌회원 아이디 UserID = "metis08" # 수집요청(requestJob)시 발급받은 작업아이디 JobID = easyFinBankService.requestJob(CorpNum, BankCode, AccountNumber, SDate, EDate, UserID) # 거래유형 배열, [I-입금 / O-출금] TradeType = ["I"] # 조회 검색어, 입금/출금액, 메모, 적요 like 검색 SearchString = "" # 페이지번호 Page = 1 # 페이지당 목록개수, 최대값 1000 PerPage = 10 # 정렬방향 [D-내림차순 / A-오름차순] Order = "D" #response = easyFinBankService.getJobState(CorpNum, JobID, UserID) response = easyFinBankService.search(CorpNum, JobID, TradeType, SearchString, Page, PerPage, Order, UserID) for tradeInfo in response.list: print(tradeInfo.remark1, tradeInfo.accIn) return render(request, 'main/Search.html', {'response': response}) except PopbillException as PE: return render(request, 'main/exception.html', { 'code': PE.code, 'message': PE.message })
def get_remaining_days(date=datetime.now()) -> int: """ 返回根据发薪日,来控制的截止时间(到发薪日还有多少天) """ # 此处逻辑有些漏洞: # 约定发薪日临周末提前发(加入3号,本来5号)时, # 一个月的结束是以提前发的(3号)日期截止, # 其实还是应该按照发薪日来作为截止时间 # 优化为判断发薪截止日是否为周末,周末就提前 # 发薪日 objective_day = salary_day_with_week_day(date) current_month_max_day = int(DateFormat(date).t()) if date.day >= objective_day: return current_month_max_day - date.day + objective_day - 1 return objective_day - date.day - 1
def post(self, request, *args, **kwargs): dict = request.POST.dict() print(request.POST) dict['id'] = request.session.get('id') dict['title'] = request.POST.get('title') dict['type'] = request.POST.get('type') dict['content'] = request.POST.get('content') dict['reg_date'] = DateFormat(datetime.now()).format('Y-m-d') form = self.form_class(dict) if form.is_valid(): career = form.save(commit=False) career.save() return HttpResponseRedirect("/noteList") return render(request, self.template_name)
def get_data(self, **kwargs): dt = lambda f: DateFormat(f).format(settings.DATETIME_FORMAT) r = [] now = datetime.datetime.now() for rt in ReduceTask.objects.all().order_by("-stop_time"): r += [ SectionRow( "#%d. %s. %s - %s" % (rt.id, "[Complete]" if rt.stop_time else "[Running]", dt(rt.start_time), dt(rt.stop_time))) ] for mt in rt.maptask_set.all().only("managed_object__name", "map_script", "status"): r += [(mt.managed_object.name, mt.map_script, mt.get_status_display())] return self.from_dataset(title=self.title, columns=["Object", "Script", "Status"], data=r)
def format_story_link_date__long(date, now=None): if not now: now = datetime.datetime.utcnow() diff = now.date() - date.date() parsed_date = DateFormat(date) if diff.days == 0: return 'Today, ' + parsed_date.format('F jS ') + date.strftime( '%I:%M%p').lstrip('0').lower() elif diff.days == 1: return 'Yesterday, ' + parsed_date.format('F jS g:ia').replace('.', '') elif date.date().timetuple()[7] == now.date().timetuple()[7]: return parsed_date.format('l, F jS g:ia').replace('.', '') else: return parsed_date.format('l, F jS, Y g:ia').replace('.', '')
def notify_new_invoice_email_dev(invoice): invoice = clean_instance(invoice, Invoice) if invoice.legacy_id or invoice.type != INVOICE_TYPE_PURCHASE: # ignore legacy invoices and only notify about developer invoices return to = [invoice.user.email] merge_vars = [ mandrill_utils.create_merge_var(MANDRILL_VAR_FIRST_NAME, invoice.user.first_name), mandrill_utils.create_merge_var('payout_title', invoice.full_title), mandrill_utils.create_merge_var( 'payout_date', DateFormat(invoice.issued_at).format('l, jS F, Y')), ] mandrill_utils.send_email('86-payout-update', to, merge_vars=merge_vars)
def yearly_amount_data(self, year=None): """ :param year: :return: total amount received in each month """ final_data = [] last_instance = self.get_queryset().latest('id') if not year: year = DateFormat(last_instance.created).format('Y') for month in range(1, 13): amount = self.get_queryset().filter(created__year=year)\ .filter(created__month=month) \ .aggregate(models.Sum('price'))['price__sum'] if not amount: amount = 0 else: amount = amount.gross final_data.append([str(year)+str(1)+str(month), float(str(amount))]) return final_data
def get_paid_limit() -> dict: """ 获取日付上线金额 """ bill_id = get_sure_month_bill() # 本月消费 total_cost = round( bill_id.day_detail.aggregate(sum=Sum('amount')).get('sum', 0) or 0, 2) # 本月剩余天数 remaining_days: int = get_remaining_days() or 1 print(remaining_days) all_day = int(DateFormat(bill_id.date).t()) true = round((bill_id.budget - total_cost) / remaining_days, 2) return { 'true': true, 'remaining_days': remaining_days, 'normal': round(true / (bill_id.budget / all_day), 2), 'normal_price': round(bill_id.budget / all_day, 2), }
def get(self, request, format=None, **kwargs): """ Return a list of all sales. """ key = '' if self.request.GET.get('date'): date = self.request.GET.get('date') summary = Item.objects.filter(created__icontains=date).values('product_name', 'product_category').annotate( c=Count('product_name', distinct=True)) \ .annotate(Sum('total_cost')) \ .annotate(Sum('quantity')).order_by('-quantity__sum') else: date = DateFormat(datetime.datetime.today()).format('Y-m-d') summary = Item.objects.filter(created__icontains=date).values('product_name', 'product_category').annotate( c=Count('product_name', distinct=True)) \ .annotate(Sum('total_cost')) \ .annotate(Sum('quantity')).order_by('-quantity__sum') return Response(summary)
def reduceTasks(accumulator, task): """ stores the tasks in the dictionary created by createWeeks(startMonday, numWeeks) args: accumulator (Dict): Dictionary to store the task task (Task): Task to store return: Dictionary: Task grouped by hours, days and weeks """ tInfo = taskInfo(task) taskDate = task.date.astimezone(timezone.get_current_timezone()) hourInfo = DateFormat(monday(taskDate)).format("b d Y") hours = accumulator[hourInfo]["week"][taskDate.weekday()]["hours"] if tInfo["htmlInfo"]["h"] in hours: hours[tInfo["htmlInfo"]["h"]].append(tInfo) else: accumulator[hourInfo]["week"][taskDate.weekday()]["hours"][ tInfo["htmlInfo"]["h"]] = [tInfo] return accumulator
def translate_seahub_time(value, autoescape=None): if isinstance(value, int) or isinstance(value, long): # check whether value is int try: val = datetime.fromtimestamp(value) # convert timestamp to datetime except ValueError as e: return "" elif isinstance(value, datetime): val = value else: return value translated_time = translate_seahub_time_str(val) if autoescape: translated_time = escape(translated_time) timestring = val.isoformat() titletime = DateFormat(val).format('r') time_with_tag = '<time datetime="'+timestring+'" is="relative-time" title="'+titletime+'" >'+translated_time+'</time>' return mark_safe(time_with_tag)