def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.id: self.created = timezone.localtime(timezone.now()) self.quantity_original = self.quantity self.modified = timezone.localtime(timezone.now()) if self.type_receipt == TYPE_RECEIPT: if not self.status: product = self.product product.inventory = product.inventory + self.quantity product.save() self.status = True elif self.type_receipt == TYPE_OBSOLETE: if not self.status: product = self.product product.inventory = product.inventory - self.quantity product.save() self.status = True elif self.type_receipt == TYPE_INACTIVADO: if not self.status: product = self.product product.inventory = product.inventory - self.quantity product.save() self.status = True return super(Receipt, self).save(*args, **kwargs)
def log_message(msg): log = "%s: %s\r\n" % (timezone.localtime(timezone.now()), msg) if not default_storage.exists(settings.ARP_IMPORT_LOG): log = "%s: Log Started\r\n%s" % (timezone.localtime(timezone.now()), log) log_file = default_storage.open(settings.ARP_IMPORT_LOG, mode="a") log_file.write(log) log_file.close()
def diary_word(request, month): document = Document() docx_title="Diary-"+str(timezone.localtime(timezone.now()).date())+".docx" time_year = int(month)/100 time_month = int(month)%100 diaries = Diary.objects.filter(time__year=time_year, time__month=time_month).order_by("-id") paragraph = document.add_paragraph(u'我的日誌:'+month) table = document.add_table(rows=1, cols=2) table.style = 'TableGrid' hdr_cells = table.rows[0].cells hdr_cells[0].text = u'日期' hdr_cells[1].text = u'內容' for diary in diaries: row_cells = table.add_row().cells row_cells[0].text = str(timezone.localtime(diary.time).strftime("%b %d %Y %H:%M:%S")) row_cells[1].text = diary.memo # Prepare document for download # ----------------------------- f = StringIO.StringIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response
def datetime2human(dt, include_time=False, days_limit=7): '''Format a datetime object for human consumption''' if isinstance(dt, datetime.datetime): dt = localtime(dt) time = dt.strftime('%H:%M') else: dt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day, tzinfo=get_default_timezone()) dt = localtime(dt) include_time = False today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) subdate = dt.date() if subdate == today: if include_time: return pgettext('humantime', 'today at {0}').format(time) else: return pgettext('humantime', 'today') elif subdate == yesterday: if include_time: return pgettext('humantime', 'yesterday at {0}').format(time) else: return pgettext('humantime', 'yesterday') else: if include_time: return date(dt, 'SHORT_DATETIME_FORMAT') else: return date(dt, 'SHORT_DATE_FORMAT')
def motion_details(request, days=3): devices = Device.objects.all() minutes = 10 start = timezone.now() - timezone.timedelta(days=days) motion_time = [] motion_count = [] delta = timezone.timedelta(minutes=minutes) while start < timezone.now(): cnt = Log.objects.filter(log_type__exact='MO', status=True, created__range=[start, start+delta]).count() motion_time.append(start) motion_count.append(cnt) start += delta # motion_datestmp = last_motion motion_time = mark_safe([timezone.localtime(m).strftime('%Y-%m-%d %H:%M:%S') for m in motion_time].__str__()) #motion_state = mark_safe([ int(m.status) for m in last_motions].__str__()) #motion_time = mark_safe(motion_time.__str__()) motion_count = mark_safe(motion_count.__str__()) range_start = mark_safe(timezone.localtime(timezone.now()-timezone.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')) range_end = mark_safe(timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S')) return render_to_response( 'motions.html', locals() )
def contest_live(request): tup=tuple() ttl=int(0) tup=(x for x in problem.objects.values_list('pcode',flat=True)) ti_me=ch_time(1) if ti_me==None : return render(request,'contest/contest_live.html',{'time_message':'No contest yet scheduled !!!'}) print ti_me crnt_time=timezone.localtime(timezone.now()) if ti_me['st']>crnt_time : return render(request,'contest/contest_live.html',{'time_message':'Contest not yet started !!!'}) if ti_me['et']<crnt_time : return render(request,'contest/contest_live.html',{'time_message':'Contest is over !!!'}) tleft=ti_me['et'] - timezone.localtime(timezone.now()) ttl=int(tleft.days*86400 + tleft.seconds) print ti_me['et'] ,' ',datetime.datetime.now() return render(request,'contest/contest_live.html',{'list':tup,'time_left':ttl})
def test_localtime_naive(self): now = datetime.datetime.now() if PY36: self.assertEqual(timezone.localtime(now), now.replace(tzinfo=timezone.LocalTimezone())) else: with self.assertRaisesMessage(ValueError, "astimezone() cannot be applied to a naive datetime"): timezone.localtime(now)
def test_moderator_controlled(self): self.assertEqual(0, self.mlist1.subscribers.count()) self.mlist1.moderator_controlled = True self.mlist1.save() self.mlist1.moderators.add(self.user1) self.mlist1.subscribers.add(self.user2) self.assertEqual(1, self.mlist1.subscribers.count()) incoming = IncomingMail.objects.create(mailing_list=self.mlist1, origin_address='*****@*****.**', subject='ahoi 3', body='I like traffic lights', sent_time=timezone.localtime(timezone.now()) - timedelta(minutes=15)) IncomingMail.objects.process_incoming() outgoing = OutgoingMail.objects.all() self.assertEqual(len(outgoing), 0) incoming = IncomingMail.objects.get(pk=incoming.id) self.assertEqual(incoming.state, 'reject') incoming = IncomingMail.objects.create(mailing_list=self.mlist1, origin_address='*****@*****.**', subject='ahoi 4', body='Who are you. Who who who who.', sent_time=timezone.localtime(timezone.now()) - timedelta(minutes=10)) IncomingMail.objects.process_incoming() outgoing = OutgoingMail.objects.all() self.assertEqual(len(outgoing), 1) income = IncomingMail.objects.get(pk=incoming.id) self.assertEqual(income.state, 'send')
def __unicode__(self): entrada = timezone.localtime(self.entrada) if timezone.is_aware(self.entrada) else self.entrada if self.saida: saida = timezone.localtime(self.saida) if timezone.is_aware(self.saida) else self.saida return u'%s - de %s a %s' % (self.membro, entrada, saida) else: return u'%s - %s' % (self.membro, entrada)
def json_data(self, include_sws_url=False): try: group_models = Group.objects.filter(course_id=self.course_id, is_deleted__isnull=True) groups = list(group_models.values_list("group_id", flat=True)) except Group.DoesNotExist: groups = [] return { "course_id": self.course_id, "term_id": self.term_id, "xlist_id": self.xlist_id, "is_sdb_type": self.is_sdb(), "added_date": localtime(self.added_date).isoformat() if ( self.added_date is not None) else None, "provisioned_date": localtime( self.provisioned_date).isoformat() if ( self.provisioned_date is not None) else None, "priority": PRIORITY_CHOICES[self.priority][1], "provisioned_error": self.provisioned_error, "provisioned_status": self.provisioned_status, "queue_id": self.queue_id, "groups": groups, "sws_url": self.sws_url() if ( include_sws_url and self.is_sdb()) else None, }
def regular_checkins(): """A recurring task which sends checkin emails to members""" # Pull the memberships that started 60 days ago and send the coworking survey # if they are still active and this was their first membership two_months_ago = timezone.localtime(timezone.now()) - timedelta(days=60) for membership in Membership.objects.filter(start_date=two_months_ago): if Membership.objects.filter(member=membership.member, start_date__lt=two_months_ago).count() == 0: if membership.member.is_active(): email.send_member_survey(membership.member.user) # Pull all the free trials from 30 days ago and send an email if they haven't been back one_month_ago = timezone.localtime(timezone.now()) - timedelta(days=30) for dropin in DailyLog.objects.filter(visit_date=one_month_ago, payment='Trial'): if DailyLog.objects.filter(member=dropin.member).count() == 1: if not dropin.member.is_active(): email.send_no_return_checkin(dropin.member.user) # Send an exit survey to members that have been gone a week. one_week_ago = timezone.localtime(timezone.now()) - timedelta(days=7) for membership in Membership.objects.filter(end_date=one_week_ago): if not membership.member.is_active(): email.send_exit_survey(membership.member.user) # Announce to the team when a new user is nearing the end of their first month almost_a_month_ago = timezone.localtime(timezone.now()) - timedelta(days=21) for membership in Membership.objects.filter(start_date=almost_a_month_ago): if Membership.objects.filter(member=membership.member, start_date__lt=almost_a_month_ago).count() == 0: if membership.member.is_active(): email.announce_member_checkin(membership.member.user)
def get_last_activity(idtopic): ''' This method return last activity of topic ''' try: comment = Comment.objects.filter( topic_id=idtopic).order_by("-date") except Exception: comment = None if comment: # Get timezone for datetime d_timezone = timezone.localtime(comment[0].date) # Format data date = formats.date_format(d_timezone, "SHORT_DATETIME_FORMAT") # Return format data more user with tag <a> html = "" html += get_path_profile(comment[0].user) html += " <p>"+str(date)+"</p>" return html else: topic = Topic.objects.get(idtopic=idtopic) # Get timezone for datetime d_timezone = timezone.localtime(topic.date) # Format data date = formats.date_format(d_timezone, "SHORT_DATETIME_FORMAT") # Return format data more user with tag <a> html = "" html += get_path_profile(topic.user) html += " <p>"+str(date)+"</p>" return html
def pub_create(request): success = False new_pub = Publication(title=request.POST['title']) if new_pub is not None: new_pub.date_added = timezone.localtime(timezone.now()) new_pub.pub_date = timezone.localtime(timezone.now() - timezone.timedelta(days=1)) new_pub.keywords = request.POST['keywords'] new_pub.save() try: author = Author.objects.get(first_name=request.POST['author_first_name'], last_name=request.POST['author_last_name']) except: author = Author(first_name=request.POST['author_first_name'], last_name=request.POST['author_last_name']) author.save() author.publication_set.add(new_pub) success = True return pub_add(request, success)
def get_sales_online(self, timestep, max): strftime, delta = self.get_timesteps_vars(timestep) now = timezone.localtime(timezone.now()) min_date = now - delta*max res = deepcopy(self.DATA_LINE) # Create datasets res['datasets'][0]['data'] = [0]*max for session in Session.objects.all(): new_dataset = deepcopy(self.DEFAULT_LINE_DATASET) new_dataset['label'] = session.space.name + " " + session.name new_dataset['borderColor'] = self.get_random_color() new_dataset['data'] = [0]*max res['datasets'].append(new_dataset) # Create labels for l in reversed(range(0, max)): date = (now - delta*l).strftime(strftime) res.get("labels").append(date) # Fill sales online mps = MultiPurchase.objects.filter(created__gt=min_date, confirmed=True).order_by('created') for mp in mps: date = timezone.localtime(mp.created).strftime(strftime) for ticket in mp.all_tickets(): try: index = res.get("labels").index(date) except ValueError: continue extra_index = self.dataset_index(res['datasets'], ticket.session.space.name + " " + ticket.session.name) res.get("datasets")[self.INDEX_MAIN].get('data')[index] += 1 res.get("datasets")[extra_index].get('data')[index] += 1 return res
def get_sales(self, timestep, max): strftime, delta = self.get_timesteps_vars(timestep) now = timezone.localtime(timezone.now()) min_date = now - delta*max res = deepcopy(self.DATA_LINE) # Create datasets res['datasets'][0]['data'] = [0]*max for ticket_window in TicketWindow.objects.all(): new_dataset = deepcopy(self.DEFAULT_LINE_DATASET) new_dataset['label'] = ticket_window.slug new_dataset['borderColor'] = self.get_random_color() new_dataset['data'] = [0]*max res['datasets'].append(new_dataset) # Create labels for l in reversed(range(0, max)): date = (now - delta*l).strftime(strftime) res.get("labels").append(date) # Fill sales sales = TicketWindowSale.objects.filter(date__gt=min_date).order_by('date') for sale in sales: date = timezone.localtime(sale.date).strftime(strftime) try: index = res.get("labels").index(date) except ValueError: continue extra_index = self.dataset_index(res['datasets'], sale.window.slug) res.get("datasets")[self.INDEX_MAIN].get('data')[index] += 1 res.get("datasets")[extra_index].get('data')[index] += 1 return res
def replay(request): if request.is_ajax(): if request.method == 'POST': ans = request.POST.get('ans', None) ans = strip_tags(ans).lstrip() url = request.POST.get('url', None) url = url.split('/')[1] if (ans == ''): resp = {"status": -1, 'error': "Сообщение не должно быть пустым"} elif len(ans) > 2000: resp = {"status": -1, 'error': "Ошибка"} elif (not Topic.objects.filter(slug = url).exists()): resp = {"status": -1, 'error': "Ошибка2"} else: topic = Topic.objects.get(slug = url) oldtopic = OldTopic.objects.get(slug = url) timezone.localtime(timezone.now()) newans = Answer.objects.create(content = ans, dtime = datetime.now(),\ user = User.objects.get(id=request.user.id), topic = topic) newans.save() topic.count_answers += 1 oldtopic.count_answers += 1 topic.save() oldtopic.save() resp = {"status": 1} else: resp = {"status": -1, 'error': "Ошибка, повторите запрос позже."} else: resp = {"status": -2} return HttpResponse(simplejson.dumps(resp), mimetype='application/javascript')
def enable_form(): """Provide time frame when registration is enabled.""" start = timezone.localtime(DateOptions.objects.get( identifier='register_unlock').date) stop = timezone.localtime(DateOptions.objects.get( identifier='register_lock').date) return start < timezone.now() < stop
def test_entry_customer_in_past(self): """ Make sure customers cannot book in the past. This test is patched to provide a constant value of 'now' """ customer = create_customer('test') dateDelta = datetime.timedelta(days=0) date = timezone.localtime(timezone.now()).date() now = timezone.localtime(timezone.now()).time() time = change_time(date, now, datetime.timedelta(hours=-1)) duration = datetime.timedelta(hours=1) entry = create_entry( dateDelta, time, duration, 'past test 1', ) entry.editor = customer self.assertRaisesMessage( ValidationError, 'Please book a date/time in the future.', entry.clean, )
def stats(self): from django.db import connection cursor = connection.cursor() sql = """ SELECT site.id, site.name, site.sortable_name, site.slug, SUM(CASE WHEN ssht.has_image = true THEN 1 ELSE 0 END), SUM(CASE WHEN ssht.has_html = true THEN 1 ELSE 0 END), MIN(ssht.timestamp), MAX(ssht.timestamp) FROM archive_site as site INNER JOIN archive_screenshot as ssht ON site.id = ssht.site_id WHERE site.status = 'active' GROUP BY 1, 2, 3, 4 """ cursor.execute(sql) results = [] for l in cursor.fetchall(): results.append({ 'id': l[0], 'name': l[1], 'sortable_name': l[2], 'slug': l[3], 'total_images': l[4], 'total_html': l[5], 'first_screenshot': timezone.localtime(l[6]), 'last_screenshot': timezone.localtime(l[7]), 'tardy': (timezone.now() - timezone.localtime(l[7])) > timedelta(days=1), }) return sorted(results, key=lambda x: x['sortable_name'])
def event_list(request): username = request.user.username event_list = Event.objects.filter( e_deadline__gt=timezone.localtime(timezone.now())) p_event_list = Event.objects.filter( e_enddate__lt=timezone.localtime(timezone.now())) return render(request, 'event_list.html', locals())
def event_record(request): username = request.user.username past_events = request.user.e_participant.filter( e_enddate__lt=timezone.localtime(timezone.now())) incoming_events = request.user.e_participant.filter( e_enddate__gt=timezone.localtime(timezone.now())) return render(request, 'event_record.html', locals())
def vote(self, request, pk=None): """ Additional call for voting to project :param request: Django Request :param pk: Project id :return: json """ project_settings = Settings.objects.all()[0] if localtime(now()) < project_settings.vote_start_time: return Response({'status': False, 'message': _('Vote not started yet')}, 409) if localtime(now()) > project_settings.vote_end_time: return Response({'status': False, 'message': _('Vote ended')}, 409) try: project = Project.objects.get(pk=pk) except Project.DoesNotExist: return Response({'status': False, 'message': _('Project does not exists')}, 404) try: team = Team.objects.get(project=project) except Team.DoesNotExist: return Response({'status': False, 'message': _('No team assigned to project')}, 404) if request.user.team == team: return Response({'status': False, 'message': _('You cannot vote for your own project')}, 400) if request.user.voted_for: if request.user.voted_for == project: # User already voted for this project return Response({'status': False, 'message': _('Already voted for this project')}, 400) # User is changing his vote unlucky_project = request.user.voted_for unlucky_project.votes -= 1 unlucky_project.save() project.votes += 1 request.user.voted_for = project project.save() request.user.save() return Response({'status': True, 'message': _('Vote Accepted')})
def submit_task(request, team_name_t): if logged_in(request): if read_access(request,team_name_t): if request.method=="POST": task_object=Task.objects.get(task_id=request.POST['task_id']) task_object.submittion_time=timezone.localtime(timezone.now()) task_object.last_modified_time=timezone.localtime(timezone.now()) task_object.submitted=True task_object.save() uploaded_file = request.FILES['file_submit'] file_text = uploaded_file.read() file_object=File(file_name=uploaded_file.name,task=task_object) with open('files/'+str(file_object.file_id),'w') as f: f.write(file_text) file_object.save() return HttpResponse("<html><h1>Successfully submitted</h1></html>") else: all_tasks = Task.objects.filter(assigned_to=User.objects.get(uname=request.COOKIES.get("username"))) context = { "tasks": all_tasks, "team": str(team_name_t), "round": get_formatted_team_name(team_name_t), } return render(request, 'home/tasks.html', context) else: raise Http404 else: return redirect("/")
def test_get_month(self): current_year = str(timezone.localtime(timezone.now()).year) current_month = str(timezone.localtime(timezone.now()).month) url = '/api/events/' + current_year + '/' + current_month + '/' response = self.__get_response(url) data = json.loads(response.content) self.assertEqual(5, len(data))
def _find_update_to_post_to_email(): """ Find updates which 1. start from today or yesterday 2. are marked as "ready" 3. have not already been posted to email """ now = timezone.now() today = timezone.localtime(now).date() yesterday = timezone.localtime(now - datetime.timedelta(days=1)).date() LOG.info('today: {} yesterday: {}'.format(today, yesterday)) try: update = Update.objects.get( ready_to_post=True, have_posted_email=False, start_date__in=(today, yesterday), ) except Update.DoesNotExist: LOG.info('No eligible Updates found.') return None if update.events.count() > 0: return update
def create_weight_entry(user, weight, post_id=None): """ Create a WeightEntry object in the database after doing input validation. """ # only allow one entry per day! if another one is made, delete the old one: since_yesterday = timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0) until_midnight = timezone.localtime(timezone.now()).replace(hour=23, minute=59, second=59, microsecond=59) try: entry = WeightEntry.objects.get(user=user, datetime__gt=since_yesterday, datetime__lt=until_midnight) entry.delete() except WeightEntry.DoesNotExist: pass # weight is not optional and must be a float if weight != '': try: weight = float(weight) except Exception: return False else: return False if post_id is not None: entry = WeightEntry.objects.get(user=user, id=post_id) entry.weight = weight entry.save() else: WeightEntry.objects.create(user=user, weight=weight) return True
def test_history_entries_render_order(self): candidate = mommy.make('core.Candidate', relatedstudent=mommy.make('core.RelatedStudent')) groupcomment = mommy.make('devilry_group.GroupComment', feedback_set__group=candidate.assignment_group, visibility=group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE) history_entry1 = mommy.make('devilry_group.GroupCommentEditHistory', group_comment=groupcomment, visibility=group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE, edited_datetime=timezone.now() - timezone.timedelta(hours=10)) history_entry2 = mommy.make('devilry_group.GroupCommentEditHistory', group_comment=groupcomment, visibility=group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE, edited_datetime=timezone.now() - timezone.timedelta(hours=14)) history_entry3 = mommy.make('devilry_group.GroupCommentEditHistory', group_comment=groupcomment, visibility=group_models.GroupComment.VISIBILITY_VISIBLE_TO_EVERYONE, edited_datetime=timezone.now() - timezone.timedelta(hours=4)) mockresponse = self.mock_http200_getrequest_htmls( cradmin_role=candidate.assignment_group, requestuser=candidate.relatedstudent.user, viewkwargs={'group_comment_id': groupcomment.id}) self.assertEqual(mockresponse.selector.list('.devilry-comment-history-item__title')[0].alltext_normalized, '{}'.format(defaultfilters.date(timezone.localtime(history_entry3.edited_datetime), 'DATETIME_FORMAT'))) self.assertEqual(mockresponse.selector.list('.devilry-comment-history-item__title')[1].alltext_normalized, '{}'.format(defaultfilters.date(timezone.localtime(history_entry1.edited_datetime), 'DATETIME_FORMAT'))) self.assertEqual(mockresponse.selector.list('.devilry-comment-history-item__title')[2].alltext_normalized, '{}'.format(defaultfilters.date(timezone.localtime(history_entry2.edited_datetime), 'DATETIME_FORMAT')))
def summary(request): def divide_delivery_window(delivery_windows, divider_func): divided = SortedDict() for delivery_window in delivery_windows: divider = divider_func(delivery_window) if divider in divided: divided[divider].append(delivery_window) else: divided[divider] = [delivery_window] return divided datetime_threshold = make_aware(datetime.now() - timedelta(days=60), get_default_timezone()) delivery_windows = DeliveryWindow.objects.filter(start__gt=datetime_threshold).order_by('-start', 'store__id') delivery_windows = filter(lambda dw: len(dw.waiting_orders) != 0, delivery_windows) divider_func = lambda dw: localtime(dw.start).date().strftime("%b %d, %a") divided_by_date = divide_delivery_window(delivery_windows, divider_func) divider_func = lambda dw: localtime(dw.start).strftime("%H:%M") + '~' + localtime(dw.end).strftime("%H:%M") divided_by_date_and_time = [(day, divide_delivery_window(divided_by_date[day], divider_func)) for day in divided_by_date] context = Context({ 'delivery_windows_divided_by_date_and_time': divided_by_date_and_time, }) template = loader.get_template('delivery/summary.html') return HttpResponse(template.render(context))
def get_today_now(): """ Obtain the current date and time as separate entities. """ today = timezone.localtime(timezone.now()).date() now = timezone.localtime(timezone.now()).time() return today, now
def get_yuncaijing_insider(): print u'Start crawl --- www.yuncaijing.com --- Time:%s' % (timezone.localtime(timezone.now()).strftime('%F %R')) try: yuncaijing_headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36' } res = requests.get('http://www.yuncaijing.com/insider/main.html', headers=yuncaijing_headers) print res.content body = BeautifulSoup(res.content, 'html.parser') soup = body.find(attrs={'class': 'main'}) for _row in soup.findAll('li', {'class': 'pr'})[:-1]: _tmp = {} news_id = _row.find('a')['href'].split('id_')[-1].split('.')[0] headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36', "X-Requested-With": 'XMLHttpRequest' } news_info_url = 'http://www.yuncaijing.com/news/modal/' + news_id if u'/insider/page_' in news_info_url: break res = requests.get(news_info_url, headers=headers) res = json.loads(res.content) res = res['data']['news'] _tmp['title'] = res['title'] _tmp['description'] = res['description'] _tmp['content_info'] = res['content'] _tmp['pub_time'] = res['inputtime'] Yuncaijing.objects.update_or_create(id=res['id'], defaults=_tmp) except Exception as e: print u'error --- %s --- Time:%s' % (e, timezone.localtime(timezone.now()).strftime('%F %R'))
def create(self, validated_data): """ Create an Order and charge the user. """ user = self.context['request'].user # if validated_data.get('target_user', None): # if user.is_staff: # user = validated_data.pop('target_user') # else: # raise serializers.ValidationError({ # 'non_field_errors': [_( # "You cannot create an order for another user without " # "admin rights." # )] # }) orderlines_data = validated_data.pop('order_lines') payment_token = validated_data.pop('payment_token', None) single_use_token = validated_data.pop('single_use_token', None) # Temporary IDs until the external profile is created. validated_data['authorization_id'] = "0" validated_data['settlement_id'] = "0" validated_data['reference_number'] = "0" validated_data['transaction_date'] = timezone.now() validated_data['user'] = user profile = PaymentProfile.objects.filter(owner=user).first() retreat_reservations = list() if single_use_token and not profile: # Create external profile try: create_profile_response = create_external_payment_profile(user) except PaymentAPIError as err: raise serializers.ValidationError({'non_field_errors': [err]}) # Create local profile profile = PaymentProfile.objects.create( name="Paysafe", owner=user, external_api_id=create_profile_response.json()['id'], external_api_url='{0}{1}'.format( create_profile_response.url, create_profile_response.json()['id'])) with transaction.atomic(): coupon = validated_data.pop('coupon', None) order = Order.objects.create(**validated_data) charge_response = None discount_amount = 0 for orderline_data in orderlines_data: OrderLine.objects.create(order=order, **orderline_data) if coupon: coupon_info = validate_coupon_for_order(coupon, order) if coupon_info['valid_use']: coupon_user = CouponUser.objects.get( user=user, coupon=coupon, ) coupon_user.uses = coupon_user.uses + 1 coupon_user.save() discount_amount = coupon_info['value'] orderline_cost = coupon_info['orderline'].cost coupon_info['orderline'].cost = (orderline_cost - discount_amount) coupon_info['orderline'].coupon = coupon coupon_info['orderline'].coupon_real_value = coupon_info[ 'value'] coupon_info['orderline'].save() else: raise serializers.ValidationError(coupon_info['error']) amount = order.total_cost tax = amount * Decimal(repr(TAX_RATE)) tax = tax.quantize(Decimal('0.01')) amount *= Decimal(repr(TAX_RATE + 1)) amount = round(amount * 100, 2) membership_orderlines = order.order_lines.filter( content_type__model="membership") package_orderlines = order.order_lines.filter( content_type__model="package") reservation_orderlines = order.order_lines.filter( content_type__model="timeslot") retreat_orderlines = order.order_lines.filter( content_type__model="retreat") need_transaction = False if membership_orderlines: need_transaction = True today = timezone.now().date() if user.membership and user.membership_end > today: raise serializers.ValidationError({ 'non_field_errors': [_("You already have an active membership.")] }) user.membership = membership_orderlines[0].content_object user.membership_end = (timezone.now().date() + user.membership.duration) user.save() membership_coupons = MembershipCoupon.objects.filter( membership__pk=membership_orderlines[0].content_object.pk) for membership_coupon in membership_coupons: coupon = Coupon.objects.create( value=membership_coupon.value, percent_off=membership_coupon.percent_off, max_use=membership_coupon.max_use, max_use_per_user=membership_coupon.max_use_per_user, details=membership_coupon.details, start_time=timezone.now(), end_time=timezone.now() + membership_orderlines[0].content_object.duration, owner=user) coupon.applicable_retreats.set( membership_coupon.applicable_retreats.all()) coupon.applicable_timeslots.set( membership_coupon.applicable_timeslots.all()) coupon.applicable_packages.set( membership_coupon.applicable_packages.all()) coupon.applicable_memberships.set( membership_coupon.applicable_memberships.all()) coupon.applicable_product_types.set( membership_coupon.applicable_product_types.all()) coupon.generate_code() coupon.save() if package_orderlines: need_transaction = True for package_orderline in package_orderlines: user.tickets += ( package_orderline.content_object.reservations * package_orderline.quantity) user.save() if reservation_orderlines: for reservation_orderline in reservation_orderlines: timeslot = reservation_orderline.content_object reservations = timeslot.reservations.filter(is_active=True) reserved = reservations.count() if timeslot.billing_price > user.tickets: raise serializers.ValidationError({ 'non_field_errors': [ _("You don't have enough tickets to make this " "reservation.") ] }) if reservations.filter(user=user): raise serializers.ValidationError({ 'non_field_errors': [ _("You already are registered to this timeslot: " "{0}.".format(str(timeslot))) ] }) if (timeslot.period.workplace and timeslot.period.workplace.seats - reserved > 0): Reservation.objects.create(user=user, timeslot=timeslot, is_active=True) # Decrement user tickets for each reservation. # OrderLine's quantity and TimeSlot's price will be # used in the future if we want to allow multiple # reservations of the same timeslot. user.tickets -= 1 user.save() else: raise serializers.ValidationError({ 'non_field_errors': [ _("There are no places left in the requested " "timeslot.") ] }) if retreat_orderlines: need_transaction = True if not (user.phone and user.city): raise serializers.ValidationError({ 'non_field_errors': [ _("Incomplete user profile. 'phone' and 'city' " "field must be filled in the user profile to book " "a retreat.") ] }) for retreat_orderline in retreat_orderlines: retreat = retreat_orderline.content_object user_waiting = retreat.wait_queue.filter(user=user) reservations = retreat.reservations.filter(is_active=True) reserved = reservations.count() if reservations.filter(user=user): raise serializers.ValidationError({ 'non_field_errors': [ _("You already are registered to this " "retreat: {0}.".format(str(retreat))) ] }) if (((retreat.seats - retreat.total_reservations - retreat.reserved_seats) > 0) or (retreat.reserved_seats and WaitQueueNotification.objects.filter( user=user, retreat=retreat))): retreat_reservations.append( RetreatReservation.objects.create( user=user, retreat=retreat, order_line=retreat_orderline, is_active=True)) # Decrement reserved_seats if > 0 if retreat.reserved_seats: retreat.reserved_seats = (retreat.reserved_seats - 1) retreat.save() else: raise serializers.ValidationError({ 'non_field_errors': [ _("There are no places left in the requested " "retreat.") ] }) if user_waiting: user_waiting.delete() if need_transaction and payment_token and int(amount): # Charge the order with the external payment API try: charge_response = charge_payment(int(round(amount)), payment_token, str(order.id)) except PaymentAPIError as err: raise serializers.ValidationError( {'non_field_errors': [err]}) elif need_transaction and single_use_token and int(amount): # Add card to the external profile & charge user try: card_create_response = create_external_card( profile.external_api_id, single_use_token) charge_response = charge_payment( int(round(amount)), card_create_response.json()['paymentToken'], str(order.id)) except PaymentAPIError as err: raise serializers.ValidationError( {'non_field_errors': [err]}) elif (membership_orderlines or package_orderlines or retreat_orderlines) and int(amount): raise serializers.ValidationError({ 'non_field_errors': [ _("A payment_token or single_use_token is required to " "create an order.") ] }) if need_transaction: if charge_response: charge_res_content = charge_response.json() order.authorization_id = charge_res_content['id'] order.settlement_id = charge_res_content['settlements'][0][ 'id'] order.reference_number = charge_res_content[ 'merchantRefNum'] else: charge_res_content = { 'card': { 'lastDigits': None, 'type': "NONE" } } order.authorization_id = 0 order.settlement_id = 0 order.reference_number = "charge-" + str(uuid.uuid4()) order.save() if need_transaction: # Send order email orderlines = order.order_lines.filter( models.Q(content_type__model='membership') | models.Q(content_type__model='package') | models.Q(content_type__model='retreat')) # Here, the 'details' key is used to provide details of the # item to the email template. # As of now, only 'retreat' objects have the 'email_content' # key that is used here. There is surely a better way to # to handle that logic that will be more generic. items = [ { 'price': orderline.content_object.price, 'name': "{0}: {1}".format(str(orderline.content_type), orderline.content_object.name), # Removed details section because it was only used # for retreats. Retreats instead have another # unique email containing details of the event. # 'details': # orderline.content_object.email_content if hasattr( # orderline.content_object, 'email_content' # ) else "" } for orderline in orderlines ] # Send order confirmation email merge_data = { 'STATUS': "APPROUVÉE", 'CARD_NUMBER': charge_res_content['card']['lastDigits'], 'CARD_TYPE': PAYSAFE_CARD_TYPE[charge_res_content['card']['type']], 'DATETIME': timezone.localtime().strftime("%x %X"), 'ORDER_ID': order.id, 'CUSTOMER_NAME': user.first_name + " " + user.last_name, 'CUSTOMER_EMAIL': user.email, 'CUSTOMER_NUMBER': user.id, 'AUTHORIZATION': order.authorization_id, 'TYPE': "Achat", 'ITEM_LIST': items, 'TAX': tax, 'DISCOUNT': discount_amount, 'COUPON': coupon, 'SUBTOTAL': round(amount / 100 - tax, 2), 'COST': round(amount / 100, 2), } plain_msg = render_to_string("invoice.txt", merge_data) msg_html = render_to_string("invoice.html", merge_data) send_mail( "Confirmation d'achat", plain_msg, settings.DEFAULT_FROM_EMAIL, [order.user.email], html_message=msg_html, ) # Send retreat informations emails for retreat_reservation in retreat_reservations: # Send info email merge_data = { 'RETREAT': retreat_reservation.retreat, 'USER': user, } plain_msg = render_to_string("retreat_info.txt", merge_data) msg_html = render_to_string("retreat_info.html", merge_data) send_mail( "Confirmation d'inscription à la retraite", plain_msg, settings.DEFAULT_FROM_EMAIL, [retreat_reservation.user.email], html_message=msg_html, ) return order
def membership(request, username): user = get_object_or_404(User, username=username) membership = Membership.objects.for_user(user) subscriptions = None sub_data = None start = None action = request.GET.get('action', None) active_members = User.helper.active_members() active_billing = User.objects.filter( profile__valid_billing=True).order_by('first_name') SubFormSet = formset_factory(SubscriptionForm) old_pkg = None bill_day = membership.bill_day if membership.package_name and membership.active_subscriptions(): old_pkg_name = membership.package_name() old_pkg = MembershipPackage.objects.get(name=old_pkg_name).id package = request.GET.get('package', old_pkg) today = localtime(now()).date() target_date = request.GET.get('target_date', None) if package != old_pkg: subscriptions = SubscriptionDefault.objects.filter(package=package) sub_data = [{ 's_id': None, 'resource': s.resource, 'allowance': s.allowance, 'start_date': today, 'end_date': None, 'username': user.username, 'created_by': request.user, 'monthly_rate': s.monthly_rate, 'overage_rate': s.overage_rate, 'paid_by': None } for s in subscriptions] action = 'change' else: subscriptions = membership.active_subscriptions() sub_data = [{ 's_id': s.id, 'package_name': s.package_name, 'resource': s.resource, 'allowance': s.allowance, 'start_date': s.start_date, 'end_date': s.end_date, 'username': user.username, 'created_by': s.created_by, 'monthly_rate': s.monthly_rate, 'overage_rate': s.overage_rate, 'paid_by': s.paid_by } for s in subscriptions] if request.method == 'POST': if 'ending' in request.POST: if request.POST['ending'] == 'today': end_date = today end_target = end_date.strftime('%Y-%m-%d') elif request.POST['ending'] == 'yesterday': end_date = today - timedelta(days=1) end_target = end_date.strftime('%Y-%m-%d') elif request.POST['ending'] == 'eop': ps, end_date = user.membership.get_period() end_target = end_date.strftime('%Y-%m-%d') else: end_target = request.POST['date-end'] return HttpResponseRedirect( reverse('staff:members:confirm', kwargs={ 'username': username, 'package': None, 'new_subs': None, 'end_target': end_target, 'start_target': None })) else: package_form = MembershipForm(request.POST) sub_formset = SubFormSet(request.POST) if sub_formset.is_valid() and package_form.is_valid(): try: with transaction.atomic(): new_subs = [] package = request.POST['package'] membership = {'package': package} for sub_form in sub_formset: paid_by = None package_name = MembershipPackage.objects.get( id=package).name s_id = sub_form.cleaned_data.get('s_id', None) resource = sub_form.cleaned_data.get( 'resource', None) allowance = sub_form.cleaned_data.get( 'allowance', None) start_date = sub_form.cleaned_data.get( 'start_date', None) if start_date: start = start_date start_date = start_date.strftime('%Y-%m-%d') end_date = sub_form.cleaned_data.get( 'end_date', None) if end_date: end_date = end_date.strftime('%Y-%m-%d') monthly_rate = sub_form.cleaned_data.get( 'monthly_rate', None) overage_rate = sub_form.cleaned_data.get( 'overage_rate', None) paid_by = sub_form.cleaned_data.get( 'paid_by', None) if resource and start_date: new_subs.append({ 's_id': s_id, 'resource': resource.id, 'package_name': package_name, 'allowance': allowance, 'start_date': start_date, 'end_date': end_date, 'monthly_rate': monthly_rate, 'overage_rate': overage_rate, 'paid_by': paid_by, 'membership': None }) end_target = start - timedelta(days=1) return HttpResponseRedirect( reverse('staff:members:confirm', kwargs={ 'username': username, 'package': membership, 'end_target': end_target, 'start_target': start, 'new_subs': new_subs })) except IntegrityError: messages.error( request, 'There was an error updating the subscriptions') else: print((sub_formset.errors)) print((package_form.errors)) messages.error( request, 'There was an error updating the subscriptions') else: package_form = MembershipForm() sub_formset = SubFormSet(initial=sub_data) context = { 'entity': user, 'subscriptions': subscriptions, 'package_form': package_form, 'package': package, 'sub_formset': sub_formset, 'active_members': active_members, 'active_billing': active_billing, 'target_date': target_date, 'bill_day': bill_day, 'action': action, } return render(request, 'staff/members/membership.html', context)
def get_issue_time(self): return timezone.localtime(self.issue_time)
def get_update_time(self): return timezone.localtime(self.update_time)
def dehydrate_trigger_at(self, obj): return timezone.localtime(obj.trigger_at).strftime("%Y-%m-%d %H:%M:%S")
def get_plot_data(self): """Retrieve all :model:`qa.TestInstance` data requested.""" self.plot_data = {'series': {}, 'events': []} now = timezone.now() dates = self.get_date(now, now - timezone.timedelta(days=365)) from_date = dates[0] to_date = dates[1] combine_data = self.request.GET.get("combine_data") == "true" relative = self.request.GET.get("relative") == "true" tests = self.request.GET.getlist("tests[]", []) test_lists = self.request.GET.getlist("test_lists[]", []) units = self.request.GET.getlist("units[]", []) statuses = self.request.GET.getlist("statuses[]", []) service_types = self.request.GET.getlist("service_types[]", []) show_events = self.request.GET.get('show_events') == 'true' # se_types = self.request.GET.getlist('service_types[]', []) if not (tests and test_lists and units and statuses): return tests = models.Test.objects.filter(pk__in=tests) test_lists = models.TestList.objects.filter(pk__in=test_lists) units = Unit.objects.filter(pk__in=units) statuses = models.TestInstanceStatus.objects.filter(pk__in=statuses) service_types = sl_models.ServiceType.objects.filter( pk__in=service_types) # test_list_names = {tl.id: tl.name for tl in test_lists} if not combine_data: # retrieve test instances for every possible permutation of the # requested test list, test & units for tl, t, u in itertools.product(test_lists, tests, units): tis = models.TestInstance.objects.filter( test_list_instance__test_list=tl, unit_test_info__test=t, unit_test_info__unit=u, status__pk__in=statuses, work_completed__gte=from_date, work_completed__lte=to_date, ).select_related( "reference", "tolerance", "unit_test_info__test", "unit_test_info__unit", "status", 'test_list_instance', 'test_list_instance__test_list').prefetch_related( "test_list_instance__comments", "test_list_instance__comments__user", ).order_by("work_completed") if tis: # tli = tis.first().test_list_instance name = "%s - %s :: %s%s" % (u.name, tl.name, t.name, " (relative to ref)" if relative else "") self.plot_data['series'][name] = { 'series_data': [ self.test_instance_to_point(ti, relative=relative) for ti in tis ], 'unit': { 'name': u.name, 'id': u.id }, 'test_list': { 'name': tl.name, 'id': tl.id }, } else: # retrieve test instances for every possible permutation of the # requested test & units for t, u in itertools.product(tests, units): tis = models.TestInstance.objects.filter( unit_test_info__test=t, unit_test_info__unit=u, status__pk__in=statuses, work_completed__gte=from_date, work_completed__lte=to_date, ).select_related("reference", "tolerance", "unit_test_info__test", "unit_test_info__unit", "status", 'test_list_instance').prefetch_related( "test_list_instance__comments", "test_list_instance__comments__user", ).order_by("work_completed") if tis: tli = tis.first().test_list_instance name = "%s :: %s%s" % (u.name, t.name, " (relative to ref)" if relative else "") self.plot_data['series'][name] = { 'series_data': [ self.test_instance_to_point(ti, relative=relative) for ti in tis ], 'unit': { 'name': u.name, 'id': u.id }, 'test_list': { 'name': tli.test_list.name, 'id': tli.test_list.id }, # 'test_list_instance': {'date': tli.created, 'id': tli.id} } if show_events: ses = sl_models.ServiceEvent.objects.filter( unit_service_area__unit__in=units, datetime_service__gte=from_date, datetime_service__lte=to_date, service_type__in=service_types).select_related( 'unit_service_area__unit', 'unit_service_area__service_area', 'service_type', 'test_list_instance_initiated_by', ).prefetch_related( 'returntoserviceqa_set', 'returntoserviceqa_set__test_list_instance', ).order_by('datetime_service') for se in ses: rtsqas = se.returntoserviceqa_set.all() self.plot_data['events'].append({ 'date': timezone.localtime(se.datetime_service), 'id': se.id, 'type': { 'id': se.service_type_id, 'name': se.service_type.name }, 'is_review_required': se.is_review_required, 'initiated_by': { 'id': se.test_list_instance_initiated_by_id, 'test_list_id': se.test_list_instance_initiated_by.test_list_id } if se.test_list_instance_initiated_by_id else '', 'rtsqas': [{ 'id': rtsqa.id, 'test_list_instance': rtsqa.test_list_instance_id, 'test_list': rtsqa.test_list_instance.test_list_id if rtsqa.test_list_instance else '' } for rtsqa in rtsqas], 'work_description': se.work_description, 'problem_description': se.problem_description, 'unit': { 'id': se.unit_service_area.unit_id, 'name': se.unit_service_area.unit.name }, 'service_area': { 'id': se.unit_service_area.service_area_id, 'name': se.unit_service_area.service_area.name, }, })
def portfolio(request): usr = sup_fn.get_user(request) lang = sup_fn.get_lang(request) # return schedule if 'active_investment' in request.META.get('PATH_INFO').split('/'): # active investment page prod_list = Product.objects.filter(status='ACTIVE') if lang == 'en': rd_prod_list = [['all', 'All Products']] elif lang == 'zh': rd_prod_list = [['all', '全部產品']] for prod in prod_list: if lang == 'en': rd_prod_list.append([prod.id, prod.name_en]) elif lang == 'zh': rd_prod_list.append([prod.id, prod.name_zh.encode('utf8')]) content = { 'lang': lang, 'cate': 'portfolio', 'sub_cate': 'active_investment', 'prod_list': rd_prod_list, } return render(request, 'peerloan/lender/active_inv.html', content) elif 'estimated_returning_schedule' in request.META.get('PATH_INFO').split( '/'): content = { 'lang': lang, 'prod_list': Product.objects.filter(status='ACTIVE') } return render(request, 'peerloan/lender/estimated_returning_schedule.html', content) this_month = datetime.strftime(timezone.localtime(timezone.now()), '%m/%Y') search_month_list = [] search_start_date = {'year': 2016, 'month': 06} for i in range(12): month = (search_start_date['month'] + i) % 12 if month == 0: month = 12 year = search_start_date['year'] + (search_start_date['month'] + i - 1) / 12 date = datetime.strptime(str(month) + '/' + str(year), '%m/%Y') search_month_list.append({ 'name': date.strftime('%B %Y'), 'value': date.strftime('%m/%Y') }) content = { 'lang': lang, 'cate': 'portfolio', 'sub_cate': 'portfolio_summary', 'title': 'Portfolio Summary', 'this_month': this_month, 'search_month_list': search_month_list, 'today': datetime.strftime(timezone.localtime(timezone.now()), '%Y/%m/%d') } if lang == 'zh': content['title'] = '投資總覽' return render(request, 'peerloan/lender/portfolio_summary.html', content)
def local_now(): return dj_timezone.localtime(dj_timezone.now())
def graphsviewbar(request, tester_name, param_name, model, side): import django from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas import matplotlib.pyplot as plt from matplotlib.figure import Figure from matplotlib import pyplot as plt import numpy as np fig = plt.Figure() ax = fig.add_subplot(211) #211 ,111 ay = fig.add_subplot(212) #fig.tight_layout() fig.tight_layout(pad=2, w_pad=0.5, h_pad=4.0) #get limit from spc.models import ParamSetting ps = ParamSetting.objects.get(tester_name=tester_name, param_name=param_name, model=model, control_side=side) titletxt = 'IR chart : %s - %s (%s)' % (tester_name, param_name, side) pd = PerformingDetail.objects.filter( param_name=param_name, perform_id__tester_name=tester_name).order_by('-datetime')[:50] minvalue_list = pd.values_list('min_value', flat=True)[::-1] maxvalue_list = pd.values_list('max_value', flat=True)[::-1] date_list = pd.values_list('datetime', flat=True)[::-1] n = pd.count() cl = np.empty(n) ucl = np.empty(n) ucl1s = np.empty(n) ucl2s = np.empty(n) lcl = np.empty(n) lcl1s = np.empty(n) lcl2s = np.empty(n) cl.fill(ps.cl) ucl.fill(ps.ucl) lcl.fill(ps.lcl) ucl1s.fill(ps.ucl1s) lcl1s.fill(ps.lcl1s) ucl2s.fill(ps.ucl2s) lcl2s.fill(ps.lcl2s) #x=np.arange(1,n+1) #ax.set_xlim(1, 50) dim = np.arange(0, n + 1) x = np.arange(1, n + 1) #x=date_list #y = np.full(n, 1) #y = np.full(n, ps.lcl*0.6) y = minvalue_list if side == 'MIN' else maxvalue_list box_plot(ay, y, '') #Center Line (CL) ax.plot(x, cl, linestyle='-', color='black', linewidth=2) ax.text(1, ps.cl, ps.cl.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'gray', 'alpha': 0.5, 'pad': 1 }) #1Sigma Upper line (1ucl) ax.plot(x, ucl1s, linestyle='--', color='green', linewidth=1) ax.text(1, ps.ucl1s, ps.ucl1s.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'green', 'alpha': 0.5, 'pad': 1 }) #1Sigma Lower line (1lcl) ax.plot(x, lcl1s, linestyle='--', color='green', linewidth=1) ax.text(1, ps.lcl1s, ps.lcl1s.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'green', 'alpha': 0.5, 'pad': 1 }) #2Sigma Upper line (2ucl) ax.plot(x, ucl2s, linestyle='--', color='orange', linewidth=1) ax.text(1, ps.ucl2s, ps.ucl2s.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'orange', 'alpha': 0.5, 'pad': 1 }) #2Sigma Upper line (2lcl) ax.plot(x, lcl2s, linestyle='--', color='orange', linewidth=1) ax.text(1, ps.lcl2s, ps.lcl2s.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'orange', 'alpha': 0.5, 'pad': 1 }) #3Sigma Upper line (3ucl) ax.plot(x, ucl, linestyle='-', color='red', linewidth=2) ax.text(1, ps.ucl, ps.ucl.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'red', 'alpha': 0.5, 'pad': 1 }) #3Sigma lower line (3lcl) ax.plot(x, lcl, linestyle='-', color='red', linewidth=2) ax.text(1, ps.lcl, ps.lcl.__format__('0.3'), ha='left', verticalalignment='bottom', color='black', wrap=True, bbox={ 'facecolor': 'red', 'alpha': 0.5, 'pad': 1 }) #xlabels = [newdate.strftime('%b-%d %I:%M %p') if True else newdate for newdate in date_list]#'%b-%d' from django.utils import timezone xlabels = [ timezone.localtime(newdate, timezone.get_default_timezone()).strftime('%b-%d') if True else newdate for newdate in date_list ] #'%b-%d' from matplotlib.ticker import MultipleLocator, FormatStrFormatter majorLocator = MultipleLocator(1) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(1) minorFormatter = FormatStrFormatter('%d') ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) ax.xaxis.set_minor_locator(minorLocator) ax.xaxis.set_major_formatter(minorFormatter) ax.plot(x, y, 'o-') #fig.xticks(dim) #fig.grid() #ax.set_xticks(date_list) labels = [ '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a1', 'b2', 'c3', 'd4', 'e5', 'f6', 'g7', 'h8', 'i9', 'j10', 'k11', 'l12', 'm13', 'n14', 'o15', 'p16', 'q17', 'r18', 's19', 't20', 'u21', 'v22', 'w23', 'x24' ] labels = ['0'] + xlabels ax.set_xticklabels(labels, rotation=70, ha='right') #for label in ax.get_xticklabels(): # label.set_rotation('vertical') #ax.plot(r.date, r.close) # rotate and align the tick labels so they look better #fig.autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar #plt.title('fig.autofmt_xdate fixes the labels') ax.set_title(titletxt) #ax.set_xticks(date_list) #ax.set_xticks(date_list) #ax.set_xticklabels(xlable , rotation=45) #Working but need to fix format #ax.set_xticklabels(date_list) #ax.set_minor_formatter(FormatStrFormatter("%b")) ax.set_ylim([(ps.lcl + (ps.lcl1s - ps.cl)), (ps.ucl + (ps.ucl1s - ps.cl))]) ax.xaxis.grid(True, 'major', linewidth=1) ax.tick_params(axis='x', pad=8) #ax.xaxis.grid(True,'minor') #fig.tight_layout() #fig.autofmt_xdate() # rotate and align the tick labels so they look better #fig.autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar #plt.title('fig.autofmt_xdate fixes the labels') #ax.imshow(X, cmap=cm.jet) fig.set_size_inches(13, 8, forward=True) #plt.savefig("image.png",bbox_inches='tight',dpi=100) canvas = FigureCanvas(fig) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response
def create(self, validated_data): """ Create a custom payment and charge the user. """ user = validated_data['user'] single_use_token = validated_data.pop('single_use_token') # Temporary IDs until the external profile is created. validated_data['authorization_id'] = "0" validated_data['settlement_id'] = "0" validated_data['transaction_date'] = timezone.now() with transaction.atomic(): custom_payment = CustomPayment.objects.create(**validated_data) amount = int(round(custom_payment.price * 100)) # Charge the order with the external payment API try: charge_response = charge_payment(amount, single_use_token, str(custom_payment.id)) except PaymentAPIError as err: raise serializers.ValidationError({'non_field_errors': [err]}) charge_res_content = charge_response.json() custom_payment.authorization_id = charge_res_content['id'] custom_payment.settlement_id = charge_res_content['settlements'][ 0]['id'] custom_payment.reference_number = charge_res_content[ 'merchantRefNum'] custom_payment.save() # TAX_RATE = settings.LOCAL_SETTINGS['SELLING_TAX'] items = [{ 'price': custom_payment.price, 'name': custom_payment.name, }] # Send custom_payment confirmation email merge_data = { 'STATUS': "APPROUVÉE", 'CARD_NUMBER': charge_res_content['card']['lastDigits'], 'CARD_TYPE': PAYSAFE_CARD_TYPE[charge_res_content['card']['type']], 'DATETIME': timezone.localtime().strftime("%x %X"), 'ORDER_ID': custom_payment.id, 'CUSTOMER_NAME': user.first_name + " " + user.last_name, 'CUSTOMER_EMAIL': user.email, 'CUSTOMER_NUMBER': user.id, 'AUTHORIZATION': custom_payment.authorization_id, 'TYPE': "Achat", 'ITEM_LIST': items, # No tax applied on custom payments. 'TAX': "0.00", 'COST': custom_payment.price, } plain_msg = render_to_string("invoice.txt", merge_data) msg_html = render_to_string("invoice.html", merge_data) send_mail( "Confirmation d'achat", plain_msg, settings.DEFAULT_FROM_EMAIL, [custom_payment.user.email], html_message=msg_html, ) return custom_payment
def serialize(self, data, serialization_format, **kwargs): return timezone.localtime(data)
def get_date_string(obj): """Helper to give the publish date in a nice British format.""" return timezone.localtime(obj.pub_date).strftime('%d %b %Y')
def queryset(self, request, queryset): if self.value() == self.CHOICES_TODAY: now = timezone.localtime(timezone.now()) date_start = now.replace(hour=0, minute=0, second=0) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, }) if self.value() == self.CHOICES_YESTERDAY: now = timezone.localtime(timezone.now()) date_end = now.replace(hour=0, minute=0, second=0) date_start = date_end - datetime.timedelta(days=1) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, '{}__lte'.format(self.field_name): date_end, }) if self.value() == self.CHOICES_LAST_14_DAYS: now = timezone.localtime(timezone.now()) date_start = now - datetime.timedelta(days=14) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, }) if self.value() == self.CHOICES_LAST_30_DAYS: now = timezone.localtime(timezone.now()) date_start = now - datetime.timedelta(days=30) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, }) if self.value() == self.CHOICES_CURRENT_WEEK: now = timezone.localtime(timezone.now()) date_start, _ = get_week_boundaries_for_dt(now) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, }) if self.value() == self.CHOICES_PREVIOUS_WEEK: now = timezone.localtime(timezone.now()) date_start, date_end = get_week_boundaries_for_dt(now - datetime.timedelta(days=7)) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, '{}__lte'.format(self.field_name): date_end, }) if self.value() == self.CHOICES_CURRENT_MONTH: now = timezone.localtime(timezone.now()) date_start, _ = get_month_boundaries_for_dt(now) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, }) if self.value() == self.CHOICES_PREVIOUS_MONTH: now = timezone.localtime(timezone.now()) current_date_start, _ = get_month_boundaries_for_dt(now) date_start, date_end = get_month_boundaries_for_dt(current_date_start - datetime.timedelta(days=1)) return queryset.filter(**{ '{}__gte'.format(self.field_name): date_start, '{}__lte'.format(self.field_name): date_end, }) if self.value() == self.CHOICES_ANY: return queryset.filter(**{ '{}__isnull'.format(self.field_name): False, }) if self.value() == self.CHOICES_NOT_SET: return queryset.filter(**{ '{}__isnull'.format(self.field_name): True, }) return None
def get_ajax(self, request, *args, **kwargs): session_id = request.GET.get('uuid') is_shared_session = request.GET.get('is_shared_session', False) is_shared_session = is_shared_session == "true" if not session_id: return JsonResponse({"message": "Ops! Session not found."}, status=404) session = { "uuid": session_id, } if is_shared_session: try: shared_session_obj = SharedSession.objects.get( uuid=session_id, shared_with=self.request.user) session_obj = shared_session_obj.refers_to session['uuid'] = session_obj.uuid shared_with_queryset_values = [] session["owner"] = False except SharedSession.DoesNotExist: return JsonResponse({"message": "Ops! Session not found."}, status=404) else: try: session_obj = Session.objects.get(username=self.request.user, uuid=session_id) shared_with_queryset = SharedSession.objects.filter( refers_to__uuid=session_id, creator=self.request.user) shared_with_queryset_values = [] for shared_session_obj in shared_with_queryset: shared_with_queryset_values.append({ "uuid": shared_session_obj.uuid, "shared_by": shared_session_obj.creator.username, "shared_with": shared_session_obj.shared_with.username, "shared_on": timezone.localtime(shared_session_obj.created_at, pytz.timezone(TIME_ZONE)), "disallow_search": shared_session_obj.disallow_search, "disallow_CAL": shared_session_obj.disallow_CAL, }) session["owner"] = True except Session.DoesNotExist: return JsonResponse({"message": "Ops! Session not found."}, status=404) session[ 'is_active_session'] = self.request.user.current_session == session_obj session['shared_with'] = shared_with_queryset_values session['topic_title'] = session_obj.topic.title session['topic_number'] = session_obj.topic.number session['topic_description'] = session_obj.topic.description session['topic_seed_query'] = session_obj.topic.seed_query session['topic_narrative'] = session_obj.topic.narrative session['strategy'] = session_obj.get_strategy_display() session['effort'] = session_obj.max_number_of_judgments session[ 'show_full_document_content'] = session_obj.show_full_document_content session['created_at'] = session_obj.created_at counters = Judgment.objects.filter( user=self.request.user, session=session_obj).aggregate( total_highlyRelevant=Count(Case(When(relevance=2, then=1))), total_relevant=Count(Case(When(relevance=1, then=1))), total_nonrelevant=Count(Case(When(relevance=0, then=1)))) session["total_highlyRelevant"] = counters["total_highlyRelevant"] session["total_nonrelevant"] = counters["total_nonrelevant"] session["total_relevant"] = counters["total_relevant"] session["total_judged"] = counters["total_highlyRelevant"] + counters[ "total_nonrelevant"] + counters["total_relevant"] return self.render_json_response(session)
def Postjson(request): if request.method=="POST": try: bodydata = request.body.decode("utf-8").replace('\n', '').replace('\r', '').replace(' ', '') jdata = json.loads(bodydata) except Exception as e: return StreamingHttpResponse("err1: " + str(request.body)) rdt = timezone.localtime().strftime("%Y-%m-%d %H:%M:%S.%f") rdt2 = timezone.localtime().strftime("%Y%m%d%H%M%S.%f") ControllerNo = jdata.get("controller").upper() SensorNo = jdata.get("sensor").upper() if ( jdata.get("measuredt") == ""): bodydata = bodydata.replace("\"measuredt\":\"\"","\"measuredt\":\"" + rdt2 + "\"") controllerip = jdata.get("ip") ipaddress = "" mydevice = 0 ipaddresss = tDevice.objects.filter(DeviceNo=ControllerNo).values('IPaddress') ipaddresss2 = tDevice.objects.filter(DeviceNo=SensorNo).values('IPaddress') mydevices = tMyServerinfo.objects.values('DeviceSeq')[:1] #update controller ip for ipaddress in ipaddresss: if controllerip != ipaddress: tDevice.objects.filter(DeviceNo=ControllerNo).update(IPaddress=controllerip) #update sensor ip( controller ip ) for ipaddress in ipaddresss2: if controllerip != ipaddress: tDevice.objects.filter(DeviceNo=SensorNo).update(IPaddress=controllerip) ordercd = "" for keyval in jdata.keys(): if keyval.upper() == "ordercd".upper(): ordercd = jdata.get(keyval).upper() curordercds = tDevice.objects.filter(DeviceNo=SensorNo).values('StatusCd') for curordercd in curordercds: curordercd = curordercd try: #update ordercd to device if (ordercd != ""): # f = open("a.txt","a") # f.write(str(ordercd)) tDevice.objects.filter(DeviceNo=SensorNo).update(StatusCd=ordercd,UptDT= rdt) #if ordercd is off stop measuring if (curordercd != "OFF") or (ordercd != ""): postdata = tMeasure( MeasureDT = rdt2,#jdata.get('measuredt'), ControllerNo = ControllerNo, SensorNo = SensorNo, OrderCd = ordercd, #on/off RcvDT = rdt, Value = bodydata, ) postdata.save() except Exception as e: #return StreamingHttpResponse("err2: " + str(e))#str(request.body)) return StreamingHttpResponse("err2: " + str(request.body)) return StreamingHttpResponse(str(request.body)) #return HttpResponse(status=200) return StreamingHttpResponse("GET")
def run_billing(bill_time=None): if not bill_time: bill_time = timezone.localtime(timezone.now()) """Generate billing records for every user who deserves it.""" bill_date = datetime.date(bill_time) logger.info("run_billing: bill_time=%s, bill_date=%s" % (bill_time, bill_date)) try: latest_billing_log = BillingLog.objects.latest() except ObjectDoesNotExist: latest_billing_log = None if latest_billing_log and not latest_billing_log.ended: logger.warning( "run_billing:The last billing log (%s) claims to be in progress. Aborting billing." % latest_billing_log) return billing_log = BillingLog.objects.create() billing_success = False bill_count = 0 try: # This should be changed to "all users w/ activity" for user in User.objects.all(): last_bill = user.profile.last_bill() if last_bill: start_date = last_bill.bill_date + timedelta(days=1) else: start_date = bill_date - timedelta(days=62) if start_date < settings.BILLING_START_DATE: start_date = settings.BILLING_START_DATE run = Run(user, start_date, bill_date) for day_index in range( 0, len(run.days) ): # look for days on which we should bill for a membership day = run.days[day_index] if day.is_membership_anniversary( ) or day.is_membership_end_date(): bill_dropins = [] bill_guest_dropins = [] recent_days = run.days[0:day_index + 1] recent_days.reverse() for recent_day in recent_days: # gather the daily logs for this user and guests under this membership if recent_day.bill: break if recent_day.daily_log: bill_dropins.append(recent_day.daily_log) for guest_daily_log in recent_day.guest_daily_logs: bill_guest_dropins.append(guest_daily_log) # now calculate the bill amount bill_amount = 0 monthly_fee = day.membership.monthly_rate if day.is_membership_end_date(): monthly_fee = 0 billable_dropin_count = max( 0, len(bill_dropins) + len(bill_guest_dropins) - day.membership.dropin_allowance) bill_amount = monthly_fee + (billable_dropin_count * day.membership.daily_rate) day.bill = Bill(bill_date=day.date, amount=bill_amount, user=user, paid_by=day.membership.paid_by, membership=day.membership) #logger.debug('saving bill: %s - %s - %s' % (day.bill, day, billable_dropin_count)) day.bill.save() bill_count += 1 day.bill.dropins = [dropin.id for dropin in bill_dropins] day.bill.guest_dropins = [ dropin.id for dropin in bill_guest_dropins ] day.bill.save() # Close out the transaction if no money is due if bill_amount == 0: transaction = Transaction(user=user, amount=0, status='closed') transaction.save() transaction.bills = [day.bill] transaction.save() # Now calculate a bill for non-member drop-ins if they exist. bill_dropins, guest_bill_dropins = run.non_member_daily_logs() if len(bill_dropins) > 0 or len(guest_bill_dropins) > 0: time_to_bill_guests = len(guest_bill_dropins) > 0 and ( bill_date - guest_bill_dropins[0].visit_date) >= timedelta(days=1) time_to_bill_dropins = len(bill_dropins) > 0 and ( bill_date - bill_dropins[0].visit_date) >= timedelta(days=1) if time_to_bill_guests or time_to_bill_dropins: bill_amount = (len(bill_dropins) + len(guest_bill_dropins) ) * settings.NON_MEMBER_DROPIN_FEE last_day = run.days[len(run.days) - 1] last_day.bill = Bill(bill_date=last_day.date, amount=bill_amount, user=user) last_day.bill.save() bill_count += 1 last_day.bill.dropins = [ dropin.id for dropin in bill_dropins ] last_day.bill.guest_dropins = [ dropin.id for dropin in guest_bill_dropins ] last_day.bill.save() billing_success = True logger.info("run_billing: Successfully created %s bills" % bill_count) except: billing_log.note = traceback.format_exc() finally: billing_log.ended = timezone.localtime(timezone.now()) billing_log.successful = billing_success billing_log.save() logger.info("run_billing: Done! Success=%s" % billing_success) if not billing_success: logger.error(billing_log.note)
def past_organization_memberships(self, target_date=None): if not target_date: target_date = localtime(now()).date() return self.user.organizationmember_set.filter( end_date__lte=target_date)
def date(self): return localtime(self.created).date()
def emergency_callback_save_callback(sender, **kwargs): contact = kwargs['instance'] contact.last_updated = localtime(now())
def duration(self): return relativedelta(localtime(now()).date(), self.first_visit)
def get_date(self, instance, *args, **kwargs): return timezone.localtime(instance.event.start).strftime("%d %b %Y %-I:%M%p")
def stale_member_date(self): three_months_ago = localtime(now()) - relativedelta(months=3) return three_months_ago
def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeTZField, self).to_representation(value)
def updated(self, fields=None): return timezone.localtime(self._destinationUpdate.updated).strftime(projectConfig.DATE_TIME_FORMAT)
def search(request, template="../templates/home.html", extra_context=None): if request.user.is_authenticated(): if request.method == "POST": AllMeal = [] meals_available = True allFavouriteMeals = request.user.profile.favourites.all() currentTime = timezone.localtime(timezone.now()) search_method = request.POST.get("search_method") search_word = request.POST.get("search_word") if search_word != "": if search_method == "1" or search_method == "2": AllMeals = Meal.objects.order_by("-addingDate") if AllMeals.count() != 0: if search_method == "1": for meal in AllMeals: if organize(meal.name) == organize(search_word): AllMeal.append(meal) else: for meal in AllMeals: if re.search( organize(search_word), organize(meal.name)): AllMeal.append(meal) elif search_method == "3" or search_method == "4": material_list = MaterialList.objects.all().order_by("-meal__addingDate") if material_list.count() != 0: if search_method == "3": for material_object in material_list: if organize(material_object.material.name) == organize(search_word): AllMeal.append(material_object.meal) else: for material_object in material_list: if re.search(organize(search_word), organize(material_object.material.name)): AllMeal.append(material_object.meal) else: user_list = User.objects.all() if user_list.count() != 0: if search_method == "5": for user_objects in user_list: if organize(user_objects.get_full_name()) == organize(search_word): user_meals = Meal.objects.filter(user=user_objects).order_by("-addingDate") if user_meals.count() != 0: for meal in user_meals: AllMeal.append(meal) else: for user_objects in user_list: if re.search(organize(search_word), organize(user_objects.get_full_name())): user_meals = Meal.objects.filter(user=user_objects).order_by("-addingDate") if user_meals.count() != 0: for meal in user_meals: AllMeal.append(meal) if len(AllMeal) == 0: meals_available = False return render(request, template, {'AllMeal':AllMeal, 'currentTime':currentTime, 'allFavouriteMeals': allFavouriteMeals, 'searchPage':True, 'meals_available':meals_available}) return HttpResponseRedirect("/home/") else: return HttpResponseRedirect("/")
def _formatted_datetime(self, dt): return format_datetime(localtime(dt), locale=get_current_babel_locale())
def getTodaysDate(): return timezone.localtime(timezone.now()).replace(hour=0, minute=0, second=0, microsecond=0)
def model_from_serializable_data(model, data, check_fks=True, strict_fks=False): pk_field = model._meta.pk pk_fields = [pk_field] # If model is a child via multitable inheritance, use parent's pk while pk_field.remote_field and pk_field.remote_field.parent_link: pk_field = pk_field.remote_field.model._meta.pk pk_fields.append(pk_field) kwargs = {pk_field.attname: data['pk']} for field_name, field_value in data.items(): try: field = model._meta.get_field(field_name) except FieldDoesNotExist: continue # Filter out reverse relations if isinstance(field, ForeignObjectRel): continue if field.remote_field and isinstance(field.remote_field, models.ManyToManyRel): related_objects = field.remote_field.model._default_manager.filter( pk__in=field_value) kwargs[field.attname] = list(related_objects) elif field.remote_field and isinstance(field.remote_field, models.ManyToOneRel): if field_value is None: kwargs[field.attname] = None else: clean_value = field.remote_field.model._meta.get_field( field.remote_field.field_name).to_python(field_value) kwargs[field.attname] = clean_value if check_fks: try: field.remote_field.model._default_manager.get( **{field.remote_field.field_name: clean_value}) except field.remote_field.model.DoesNotExist: if field.remote_field.on_delete == models.DO_NOTHING: pass elif field.remote_field.on_delete == models.CASCADE: if strict_fks: return None else: kwargs[field.attname] = None elif field.remote_field.on_delete == models.SET_NULL: kwargs[field.attname] = None else: raise Exception( "can't currently handle on_delete types other than CASCADE, SET_NULL and DO_NOTHING" ) else: value = field.to_python(field_value) # Make sure datetimes are converted to localtime if isinstance(field, models.DateTimeField ) and settings.USE_TZ and value is not None: default_timezone = timezone.get_default_timezone() if timezone.is_aware(value): value = timezone.localtime(value, default_timezone) else: value = timezone.make_aware(value, default_timezone) kwargs[field.name] = value if data['pk'] is not None: # If model has non-serializable fields (serialize=False), their data has to be # restored from database if possible restore_fields = [] # Collect non-serializable fields to be restored (excluding pk fields) for field in model._meta.fields: if field not in pk_fields and not field.serialize: restore_fields.append(field.name) if restore_fields: try: obj_from_db = model._default_manager.get(pk=data['pk']) for field_name in restore_fields: kwargs[field_name] = getattr(obj_from_db, field_name) except model.DoesNotExist: # In this case model is being created with explicit pk # so nothing can be restored pass obj = model(**kwargs) if data['pk'] is not None: # Set state to indicate that this object has come from the database, so that # ModelForm validation doesn't try to enforce a uniqueness check on the primary key obj._state.adding = False return obj
def dashboard_view(request, show_widgets=True, show_expired=False, ignore_dashboard_types=None, show_welcome=False): """Process and show the dashboard, which includes activities, events, and widgets.""" user = request.user if user.is_student and settings.ENABLE_PRE_EIGHTH_LOCATION_REDIRECT and request.COOKIES.get("seen_eighth_location", "") != "1": now = timezone.localtime() try: today_8 = Day.objects.today().day_type.blocks.filter(name__contains="8") if today_8: first_start_time = time(today_8[0].start.hour, today_8[0].start.minute) last_start_time = time(today_8.last().start.hour, today_8.last().start.minute) first_start_date = datetime.combine(now.today(), first_start_time) last_start_date = datetime.combine(now.today(), last_start_time) if first_start_date - timedelta(minutes=30) < datetime.combine(now.today(), now.time()) < last_start_date + timedelta(minutes=20): return redirect(reverse("eighth_location")) except AttributeError: pass announcements_admin = user.has_admin_permission("announcements") events_admin = user.has_admin_permission("events") if not show_expired: show_expired = "show_expired" in request.GET show_all = request.GET.get("show_all", "0") != "0" if "show_all" not in request.GET and request.user.is_eighthoffice: # Show all by default to 8th period office show_all = True # Include show_all postfix on next/prev links paginate_link_suffix = "&show_all=1" if show_all else "" is_index_page = request.path_info in ["/", ""] context = { "prerender_url": get_prerender_url(request), "user": user, "announcements_admin": announcements_admin, "events_admin": events_admin, "is_index_page": is_index_page, "show_all": show_all, "paginate_link_suffix": paginate_link_suffix, "show_expired": show_expired, } # Get list of announcements items = get_announcements_list(request, context) # Paginate announcements list context, items = paginate_announcements_list(request, context, items) user_hidden_announcements = Announcement.objects.hidden_announcements(user).values_list("id", flat=True) user_hidden_events = Event.objects.hidden_events(user).values_list("id", flat=True) if ignore_dashboard_types is None: ignore_dashboard_types = [] context.update( { "hide_announcements": True, "hide_events": True, "user_hidden_announcements": user_hidden_announcements, "user_hidden_events": user_hidden_events, "ignore_dashboard_types": ignore_dashboard_types, } ) is_student = user.is_student is_teacher = user.is_teacher is_senior = user.is_senior is_global_admin = user.member_of("admin_all") and user.is_superuser show_admin_widget = is_global_admin or announcements_admin or user.is_eighth_admin eighth_sponsor = user.get_eighth_sponsor() # the URL path for forward/back buttons view_announcements_url = "index" if show_widgets: dashboard_title = "Dashboard" dashboard_header = "Dashboard" elif show_expired: dashboard_title = dashboard_header = "Announcement Archive" view_announcements_url = "announcements_archive" else: dashboard_title = dashboard_header = "Announcements" num_senior_destinations = len(Senior.objects.filled()) try: dash_warning = settings.DASH_WARNING except Exception: dash_warning = None fcps_emerg = get_fcps_emerg(request) ap_week = get_ap_week_warning(request) if fcps_emerg: dash_warning = fcps_emerg elif ap_week: dash_warning = ap_week context.update( { "dash_warning": dash_warning, "show_widgets": show_widgets, "show_expired": show_expired, "show_near_graduation_message": is_senior and (timezone.now().date() + timedelta(days=settings.NEAR_GRADUATION_DAYS) >= get_senior_graduation_date().date()), "view_announcements_url": view_announcements_url, "dashboard_title": dashboard_title, "dashboard_header": dashboard_header, "is_student": is_student, "is_teacher": is_teacher, "is_senior": is_senior, "is_global_admin": is_global_admin, "show_admin_widget": show_admin_widget, "eighth_sponsor": eighth_sponsor, "num_senior_destinations": num_senior_destinations, } ) if settings.TJSTAR_MAP: context.update(get_tjstar_mapping(request.user)) ####### if settings.ENABLE_HYBRID_EIGHTH: context.update({"hybrid": True}) ####### if show_widgets: context = add_widgets_context(request, context) if announcements_admin: all_waiting = AnnouncementRequest.objects.filter(posted=None, rejected=False).this_year() awaiting_teacher = all_waiting.filter(teachers_approved__isnull=True) awaiting_approval = all_waiting.filter(teachers_approved__isnull=False) context.update({"awaiting_teacher": awaiting_teacher, "awaiting_approval": awaiting_approval}) self_awaiting_teacher = AnnouncementRequest.objects.filter(posted=None, rejected=False, teachers_requested=request.user).this_year() context.update({"self_awaiting_teacher": self_awaiting_teacher}) if is_april_fools_day(): messages.success(request, "Happy April Fools Week!") messages.error(request, "It's Ion, not ION.") messages.info(request, "Roses and red, violets are blue and your sysadmins want to tell you:") if show_welcome: return render(request, "welcome/student.html", context) else: return render(request, "dashboard/dashboard.html", context)
def date_hour(self, timestamp): return localtime(timestamp).strftime("%H")