def queryset(self, request, queryset): daystart = timezone.make_aware(datetime.combine(timezone.localdate(), time.min)) dayend = timezone.make_aware(datetime.combine(timezone.localdate(), time.max)) # using daystart and dayend because I can't directly filter using start_date.day if self.value() == 'today': return queryset.filter(start_date__gte=daystart, start_date__lte=dayend) if self.value() == 'tomorrow': daystart += timedelta(days=1) dayend += timedelta(days=1) return queryset.filter(start_date__gte=daystart, start_date__lte=dayend) if self.value() == 'week': dayend += timedelta(days=7) return queryset.filter(start_date__gte=daystart, start_date__lte=dayend) if self.value() == 'month': dayend += timedelta(days=30) return queryset.filter(start_date__gte=daystart, start_date__lte=dayend) if self.value() == 'last_week': daystart -= timedelta(days=7) return queryset.filter(start_date__gte=daystart, start_date__lte=dayend)
def queryset(self, request, queryset): if self.value() == 'none': return queryset.filter(birthday = None) lowdate = timezone.localdate() #TZ aware hidate = timezone.localdate() if self.value() == 'today': return queryset.filter(create_query(lowdate, hidate)) if self.value() == 'tomorrow': lowdate += timedelta(days=1) hidate += timedelta(days=1) return queryset.filter(create_query(lowdate, hidate)) if self.value() == 'yesterday': lowdate -= timedelta(days=1) hidate -= timedelta(days=1) return queryset.filter(create_query(lowdate, hidate)) if self.value() == 'week': hidate += timedelta(days=7) return queryset.filter(create_query(lowdate, hidate)) if self.value() == 'last_week': lowdate -= timedelta(days=7) return queryset.filter(create_query(lowdate, hidate))
def registered_or_raise(self, **kwargs): """Raises an exception if subject is not registered or if subject's DoB precedes the offstudy_datetime. """ try: obj = RegisteredSubject.objects.get( subject_identifier=self.subject_identifier) except ObjectDoesNotExist: raise OffstudyError( f'Unknown subject. Got {self.subject_identifier}.', code=SUBJECT_NOT_REGISTERED) else: if not obj.dob: raise OffstudyError( 'Invalid date of birth. Got None', code=INVALID_DOB) else: if obj.dob > timezone.localdate(self.offstudy_datetime): formatted_date = timezone.localtime( self.offstudy_datetime).strftime(EDC_DATETIME_FORMAT) raise OffstudyError( f'Invalid off-study date. ' f'Off-study date may not precede date of birth. ' f'Got \'{formatted_date}\'.', code=OFFSTUDY_DATETIME_BEFORE_DOB)
def timezone_today(): """ Return the current date in the current time zone. """ if settings.USE_TZ: return timezone.localdate() else: return datetime.date.today()
def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) if PY36: self.assertEqual(timezone.localdate(naive), datetime.date(2015, 1, 1)) self.assertEqual(timezone.localdate(naive, timezone=EAT), datetime.date(2015, 1, 1)) else: with self.assertRaisesMessage(ValueError, 'astimezone() cannot be applied to a naive datetime'): timezone.localdate(naive) with self.assertRaisesMessage(ValueError, 'astimezone() cannot be applied to a naive datetime'): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual(timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch('django.utils.timezone.now', return_value=aware): self.assertEqual(timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31))
def dashboard(request): messages = [] message = {} has_delete_permission = request.user.has_perm('scheduler.add_edit_post') if request.method == "POST" and has_delete_permission: post_id = request.POST.get('post_id_to_delete', None) post = get_object_or_404(SMPost, pk=post_id) post.delete() message = { "mtype": "success", "mtext": "Your post was deleted", } alt_date = None if request.method == "GET": date_change_str = request.GET.get('date', None) if date_change_str: cal = pdt.Calendar() date_change = cal.parse(date_change_str) if date_change[1] == 1 or date_change[1] == 3: alt_date = datetime.date( date_change[0][0], date_change[0][1], date_change[0][2]) if alt_date: view_date = alt_date else: view_date = timezone.localdate() today_posts = SMPost.objects.filter(pub_date=view_date) lost_posts = SMPost.objects.filter(pub_date=None) site_message = MeowSetting.objects.get( setting_key='site_message').setting_value if request.session.get("message", None): temp_message = request.session.pop("message") messages.append({ "mtype": "success", "mtext": temp_message, }) messages.append(message) context = { "user": request.user, "sections": Section.objects.all(), # Turning this feature off for now # "smposts": zip(list(chain(today_posts, lost_posts)), get_analytics(list(chain(today_posts, lost_posts)))), "smposts": list(chain(today_posts, lost_posts)), "messages": messages, "view_date": view_date, "site_settings": get_settings() } return render(request, 'scheduler/dashboard.html', context)
def get_queryset(self): today = timezone.localdate() return super() \ .get_queryset() \ .annotate(attendees_count=models.Count('attendee', distinct=True)) \ .annotate(last_date=models.Max('eventdate__date')) \ .annotate(activity_proposal_is_open=models.Case( models.When(models.Q(limit_proposal_date__gte=today), then=True), default=False, output_field=models.BooleanField() )) \ .annotate(registration_is_open=models.Case( models.When(models.Q(last_date__gte=today), then=True), default=False, output_field=models.BooleanField() ))
def add(request): if not request.user.has_perm('scheduler.add_edit_post'): return redirect('/') post_id = -1 if request.method == "POST" and request.user.has_perm('scheduler.add_edit_post'): post = SMPost() edit(request, -1, post) post_id = post.id return redirect("/edit/" + str(post.id) + "/?add=true") site_message = MeowSetting.objects.get( setting_key='site_message').setting_value context = { "user": request.user, "sections": Section.objects.all(), "today": timezone.localdate(), "twitter_limit": MeowSetting.objects.get(setting_key='twitter_character_limit').setting_value, "site_settings": get_settings(), } return render(request, 'scheduler/edit.html', context)
def days_from_last_inspection(self): last_inspection = self.date_of_last_technical_inspection now = timezone.localdate() difference = now - last_inspection return difference.days
from django.http import HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.views.generic import ListView, DetailView, UpdateView, DeleteView from django.shortcuts import render from . import forms from . import models from django.db.models import Sum from django.utils import timezone import time from .helpers import get_month_name from django.db.models import Q import re from django.contrib.auth.models import User today = timezone.localdate() # Create your views here. class ExpendListView(ListView): model = models.Expend template_name = 'expend/expend_list.html' ordering = ['-added_date'] context_object_name = 'filter_date' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter_date_user'] = models.Expend.objects.filter( by_user__exact=self.request.user.username).order_by('-added_date') context['sum_user_expend_amount'] = models.Expend.objects.filter( by_user__exact=self.request.user.username).aggregate( Sum('expend_amount')).get('expend_amount__sum', 0.00) context['sum_user_expend_amount_verified'] = models.Expend.objects.filter(
def remain_days(self): if not self.expire_at: return 0 return (self.expire_at - timezone.localdate()).days
def days_valid(self): if self.expires is None: return 999999 return (self.expires - timezone.localdate()).days
def is_today(self): return self.day == localdate()
def _default_title(): now = timezone.localdate() git_directory = os.path.join(settings.PROJECT_ROOT, ".git") branch_name = git_branch(git_directory=git_directory) return "{0}/{1} ({2}) Maintenance".format(now.month, now.day, branch_name)
def get(self, request, *args, **kwargs): event_id = self.kwargs.get('event_id') melb_date = sys_time.localdate(sys_time.now()) return render(request, self.template_name)
def edit(request, post_id, post=None): if not post: post = get_object_or_404(SMPost, pk=post_id) if (post.sent and not post.sent_error) or not can_edit_post(request.user, post) or post.sending: message = { "mtype": "status", } if post.sent: message['mtext'] = "This post has already been sent and cannot be edited" elif not can_edit_post(request.user, post): message['mtext'] = "You do not have permission to edit this post" elif post.sending: message['mtext'] = "This post is currently sending and cannot be edited" site_message = MeowSetting.objects.get( setting_key='site_message').setting_value context = { "user": request.user, "sections": Section.objects.all(), "post": post, "message": message, "site_settings": get_settings(), } return render(request, 'scheduler/view.html', context) message = {} if request.method == "POST" and can_edit_post(request.user, post): post.story_url = request.POST.get('url', None).strip(" \t\n\r") if len(post.story_url) > 4 and post.story_url[0:4] != "http": try: index_of_protocol = post.story_url.index("://") if index_of_protocol <= 5: post.story_url = "http" + \ post.story_url[post.story_url.index("://"):] except: post.story_url = "http://" + post.story_url post.slug = request.POST.get('slug', None) try: post.section = Section.objects.get( pk=request.POST.get('section', None)) except: post.section = None post.post_twitter = request.POST.get('tweet', None) post.post_facebook = request.POST.get('fb', None) post.post_instagram = request.POST.get('ig', None) post.post_notes = request.POST.get('notes', None) # date_str = request.POST.get('pub_date', None) # time_str = request.POST.get('pub_time', None) date_time_str = request.POST.get('pub_date_time', None) # Date cal = pdt.Calendar() date_parsed = cal.parse(date_time_str) time_parsed = cal.parse(date_time_str) if date_parsed[1] == 1 or date_parsed[1] == 3: post.pub_date = datetime.date( date_parsed[0][0], date_parsed[0][1], date_parsed[0][2]) post.pub_time = datetime.time(time_parsed[0][3], time_parsed[0][4]) else: post.pub_date = None post.pub_time = None # Time # time_parsed = cal.parse(time_str) # if time_parsed[1] == 2 or time_parsed[1] == 3: # post.pub_time = datetime.time(time_parsed[0][3], time_parsed[0][4]) # else: # post.pub_time = None # Checkboxes if request.user.has_perm('scheduler.approve_copy'): if request.POST.get('approve-copy', False) == 'on': if post.pub_ready_copy == False: post.pub_ready_copy_user = request.user post.pub_ready_copy = True else: post.pub_ready_copy = False post.pub_ready_copy_user = None if request.user.has_perm('scheduler.approve_online'): if request.POST.get('approve-online', False) == 'on': if post.pub_ready_online == False: post.pub_ready_online_user = request.user post.pub_ready_online = True else: post.pub_ready_online = False post.sent_error = False post.sent = False post.pub_ready_online_user = None post.last_edit_user = request.user post.save() message = { "mtype": "success", "mtext": "Your changes were saved!", } if request.method == "GET" and request.user.has_perm('scheduler.add_edit_post'): if request.GET.get('add', None) == "true": message = { "mtype": "success", "mtext": "Your post was successfully created!", } site_message = MeowSetting.objects.get( setting_key='site_message').setting_value context = { "user": request.user, "sections": Section.objects.all(), "post": post, "today": timezone.localdate(), "message": message, "twitter_limit": MeowSetting.objects.get(setting_key='twitter_character_limit').setting_value, "site_settings": get_settings(), } return render(request, 'scheduler/edit.html', context)
def all_home(request): if request.method == "GET": from django.utils.timezone import localdate from django.utils.dateparse import parse_date from datetime import datetime, timedelta d = request.GET.get('d', None) print(request.get_full_path()) if d is None: if not request.get_full_path() == '/all/': return redirect(reverse('baseapp:all_home')) today_str = str(localdate()) today_obj = datetime(int(today_str.split('-')[0]), int(today_str.split('-')[1]), int(today_str.split('-')[2])) yesterday_obj = today_obj - timedelta(days=1) yesterday_str = str(yesterday_obj).split(' ')[0] return render(request, 'baseapp/all_home.html', {'day': today_str, 'yesterday': yesterday_str, 'today': today_str, 'tomorrow': ''}) else: date = parse_date(d) if date is None: return redirect(reverse('baseapp:all_home')) else: today_str = str(localdate()) day_str = str(date) if today_str == day_str: return redirect(reverse('baseapp:all_home')) # first_post_created = Post.objects.first().created # origin_str = str(first_post_created).split(' ')[0] origin_str = '2018-11-10' date_1 = None date_2 = None date_3 = None try: date_1 = datetime.strptime(origin_str, '%Y-%m-%d') date_2 = datetime.strptime(day_str, '%Y-%m-%d') date_3 = datetime.strptime(today_str, '%Y-%m-%d') except Exception as e: return redirect(reverse('baseapp:all_home')) if not date_1 <= date_2 <= date_3: return redirect(reverse('baseapp:all_home')) day_obj = datetime(int(day_str.split('-')[0]), int(day_str.split('-')[1]), int(day_str.split('-')[2])) yesterday_obj = day_obj - timedelta(days=1) yesterday_str = str(yesterday_obj).split(' ')[0] tomorrow_obj = day_obj + timedelta(days=1) tomorrow_str = str(tomorrow_obj).split(' ')[0] return render(request, 'baseapp/all_home.html', {'day': day_str, 'yesterday': yesterday_str, 'today': today_str, 'tomorrow': tomorrow_str})
def operator_vehicles(request, slug=None, parent=None): operators = Operator.objects.select_related('region') if slug: try: operator = operators.get(slug=slug.lower()) except Operator.DoesNotExist: operator = get_object_or_404(operators, operatorcode__code=slug, operatorcode__source__name='slug') vehicles = operator.vehicle_set.filter(withdrawn=False) elif parent: operators = list(operators.filter(parent=parent)) vehicles = Vehicle.objects.filter( operator__in=operators, withdrawn=False).select_related('operator') if not operators: raise Http404 operator = operators[0] vehicles = vehicles.order_by('fleet_number', 'fleet_code', 'reg', 'code') if not parent: vehicles = vehicles.annotate( feature_names=StringAgg('features__name', ', ')) pending_edits = VehicleEdit.objects.filter( approved=None, vehicle=OuterRef('id')).only('id') vehicles = vehicles.annotate(pending_edits=Exists(pending_edits)) vehicles = vehicles.select_related('latest_journey') vehicles = vehicles.select_related('livery', 'vehicle_type') submitted = False revisions = False breadcrumb = [operator.region, operator] form = request.path.endswith('/edit') if form: if not request.user.is_authenticated: return redirect(f'/accounts/login/?next={request.path}') if request.user.trusted is False: raise PermissionDenied breadcrumb.append(Vehicles(operator)) initial = { 'operator': operator, 'other_colour': '#ffffff', } if request.method == 'POST': form = EditVehiclesForm(request.POST, initial=initial, operator=operator, user=request.user) if not form.has_really_changed(): form.add_error(None, 'You haven\'t changed anything') elif form.is_valid(): data = { key: form.cleaned_data[key] for key in form.changed_data } vehicle_ids = request.POST.getlist('vehicle') now = timezone.now() revisions, changed_fields = do_revisions( vehicle_ids, data, request.user) if revisions and changed_fields: Vehicle.objects.bulk_update( (revision.vehicle for revision in revisions), changed_fields) for revision in revisions: revision.datetime = now VehicleRevision.objects.bulk_create(revisions) revisions = len(revisions) if data: # this will fetch the vehicles list # - slightly important that it occurs before any change of operator ticked_vehicles = [ v for v in vehicles if str(v.id) in vehicle_ids ] edits = [ get_vehicle_edit(vehicle, data, now, request) for vehicle in ticked_vehicles ] edits = VehicleEdit.objects.bulk_create(edit for edit in edits if edit) submitted = len(edits) if 'features' in data: for edit in edits: edit.features.set(data['features']) form = EditVehiclesForm(initial=initial, operator=operator, user=request.user) else: form = EditVehiclesForm(initial=initial, operator=operator, user=request.user) if operator.name == 'National Express': vehicles = sorted(vehicles, key=lambda v: v.notes) if not vehicles: raise Http404 if parent: paginator = Paginator(vehicles, 1000) page = request.GET.get('page') vehicles = paginator.get_page(page) else: paginator = None features_column = not parent and any(vehicle.feature_names for vehicle in vehicles) columns = set(key for vehicle in vehicles if vehicle.data for key in vehicle.data) for vehicle in vehicles: vehicle.column_values = [ vehicle.data and vehicle.data_get(key) or '' for key in columns ] if not parent: today = timezone.localdate() for vehicle in vehicles: if vehicle.latest_journey: when = vehicle.latest_journey.datetime vehicle.last_seen = { 'service': vehicle.latest_journey.route_name, 'when': when, 'today': timezone.localdate(when) == today, } context = { 'breadcrumb': breadcrumb, 'parent': parent, 'operators': parent and operators, 'object': operator, 'map': any(vehicle.latest_location_id for vehicle in vehicles), 'vehicles': vehicles, 'paginator': paginator, 'code_column': any(vehicle.fleet_number_mismatch() for vehicle in vehicles), 'branding_column': any(vehicle.branding and vehicle.branding != 'None' for vehicle in vehicles), 'name_column': any(vehicle.name for vehicle in vehicles), 'notes_column': any(vehicle.notes and vehicle.notes != 'Spare ticket machine' for vehicle in vehicles), 'features_column': features_column, 'columns': columns, 'edits': submitted, 'revisions': revisions, 'revision': revisions and revision, 'form': form, } if not parent and not form: context['map'] = any(vehicle.latest_location_id for vehicle in vehicles) return render(request, 'operator_vehicles.html', context)
def attended_today(self): return EventUserAttendanceDate.objects.filter( event_user=self, date__date=timezone.localdate()).exists()
import types from datetime import timedelta import pytest from django.conf import settings from django.utils import timezone from tests.conftest import twilio_vcr from apostello import logs, models from site_config.models import SiteConfiguration today = timezone.localdate() class MockMsg: def __init__(self, from_): self.sid = 'a' * 34 self.body = 'test message' self.from_ = from_ self.to = settings.to = '447922537999' self.date_created = timezone.now() self.date_sent = timezone.now() self.status = 'unknown' @pytest.mark.django_db class TestImportLogs: """ Test log imports. Unable to test this properly as Twilio raises an exception when test
def current_date(): d = timezone.localdate() return (d.month, d.day)
def today_conference(): return timezone.localdate(timezone.now())
def clean_birth_date(self): data = self.cleaned_data['birth_date'] if data and data > timezone.localdate(timezone.now()): raise forms.ValidationError("Укажите корректную дату рождения") return data
def is_past_due(self): return not self.paid if self.paid else self.due_date < localdate()
class JobApplicationWithApprovalNotCancellableFactory( JobApplicationWithApprovalFactory): hiring_start_at = timezone.localdate() - relativedelta(days=5) hiring_end_at = timezone.localdate() + relativedelta(years=2, days=-5)
def attended_today(self): return AttendeeAttendanceDate.objects.filter( attendee=self, date__date=timezone.localdate()).exists()
def year_list(): return range(2019, timezone.localdate().year + 1)
def today(self): return self.filter(day=localdate())
def get_attendance(): """ Returns attendance object """ return DailyAttendance.objects.filter( date_created=timezone.localdate()).first()
def test_check_auth_basic_per_request(self): settings.CHECK_AUTH_BASIC_PER_REQUEST = True self.test_users = [("*****@*****.**", "*****@*****.**", True) ] self.test_usergroups = [("all_user", ["*@*.*"], None, None)] self.test_usergroupauthorization = [("all_user", "*", "*", None)] self.populate_testdata() #test sso token auth user = self.test_users["*****@*****.**"] for username, usertoken in ((user.username, user.token), ): token = usertoken.token res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.status_code, 200, msg="Should return 200 response for authenticated request") self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.status_code, 200, msg="Should return 200 response for authenticated request") self.assertEqual(res.get('X-auth-cache-hit'), 'success', msg="Already authenticated, should hit the cache") usertoken.enabled = False usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 401, msg= "Should return 401 response because user's token was disabled") usertoken.enabled = True usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 200, msg= "Should return 200 response because user's token was enabled") res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.status_code, 200, msg= "Should return 200 response because user's token was enabled") self.assertEqual(res.get('X-auth-cache-hit'), 'success', msg="Already authenticated, should hit the cache") usertoken.expired = timezone.localdate() - timedelta(days=1) usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 401, msg= "Should return 401 response because user's token was expired") usertoken.expired = timezone.localdate() + timedelta(days=1) usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 200, msg= "Should return 200 response because user's token was extended") res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.status_code, 200, msg= "Should return 200 response because user's token was extended") self.assertEqual(res.get('X-auth-cache-hit'), 'success', msg="Already authenticated, should hit the cache") usertoken.token = None usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 401, msg= "Should return 401 response because user's token was cleared") usertoken.token = token usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 200, msg= "Should return 401 response because user's token was resaved") res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.status_code, 200, msg= "Should return 401 response because user's token was resaved") self.assertEqual(res.get('X-auth-cache-hit'), 'success', msg="Already authenticated, should hit the cache") usertoken.generate_token() usertoken.save() res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 401, msg= "Should return 401 response because user's token was regenerated" ) res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, usertoken.token)) self.assertEqual( res.has_header('X-auth-cache-hit'), False, msg="Should authenticate the user without hit the cache") self.assertEqual( res.status_code, 200, msg="Should return 200 response because new token was used") res = self.client.get(self.auth_basic_url, HTTP_AUTHORIZATION=self.basic_auth( username, usertoken.token)) self.assertEqual( res.status_code, 200, msg="Should return 200 response because new token was used") self.assertEqual(res.get('X-auth-cache-hit'), 'success', msg="Already authenticated, should hit the cache")
def update_stats(self, shortcode): year, week, _ = localdate().isocalendar() ts = TinyURLStats(shortcode=shortcode, week=week, year=year) ts.save()
def get_high_risk_student(cls): five_days_ago = timezone.localdate() - timedelta(days=5) return cls.objects.filter(score__gte=11, start_time__gte=day_start(five_days_ago)) \ .order_by('-start_time') \ .values('student_netid', 'start_time')
def serveWeek(self, request, year=None, week=None): """Weekly calendar view.""" myurl = self.get_url(request) def myUrl(urlYear, urlWeek): if (urlYear < 1900 or urlYear > 2099 or urlYear == 2099 and urlWeek == 53): return None if urlWeek == 53 and num_weeks_in_year(urlYear) == 52: urlWeek = 52 return myurl + self.reverse_subpage('serveWeek', args=[urlYear, urlWeek]) today = timezone.localdate() thisYear, thisWeekNum, dow = gregorian_to_week_date(today) if year is None: year = thisYear if week is None: week = thisWeekNum year = int(year) week = int(week) firstDay, lastDay, prevYearNumWeeks, yearNumWeeks = week_info( year, week) if week == 53 and yearNumWeeks == 52: raise Http404("Only 52 weeks in {}".format(year)) eventsInWeek = self._getEventsByDay(request, firstDay, lastDay) if firstDay.year >= 1900: monthlyUrl = myurl + self.reverse_subpage( 'serveMonth', args=[firstDay.year, firstDay.month]) else: monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[1900, 1]) listUrl = myurl + self.reverse_subpage('serveUpcoming') prevWeek = week - 1 prevWeekYear = year if prevWeek == 0: prevWeek = prevYearNumWeeks prevWeekYear -= 1 nextWeek = week + 1 nextWeekYear = year if nextWeek > yearNumWeeks: nextWeek = 1 nextWeekYear += 1 cxt = self._getCommonContext(request) cxt.update({ 'year': year, 'week': week, 'yesterday': today - dt.timedelta(1), 'prevWeekUrl': myUrl(prevWeekYear, prevWeek), 'nextWeekUrl': myUrl(nextWeekYear, nextWeek), 'prevYearUrl': myUrl(year - 1, week), 'nextYearUrl': myUrl(year + 1, week), 'thisWeekUrl': myUrl(thisYear, thisWeekNum), 'monthlyUrl': monthlyUrl, 'listUrl': listUrl, 'weekName': _("Week {weekNum}").format(weekNum=week), 'weekdayAbbr': weekday_abbr, 'events': [eventsInWeek] }) cxt.update(self._getExtraContext("week")) return TemplateResponse(request, "joyous/calendar_week.html", cxt)
def unpublished(self): query = self.filter(publication_date__gt=timezone.localdate()) return query
def get_end_date_from_session(entity_slug: str, request) -> date: session_end_date_filter = get_end_date_session_key(entity_slug) end_date = request.session.get(session_end_date_filter) end_date = parse_date(end_date) if end_date else localdate() return end_date
def today_global(): return timezone.localdate(timezone.now(), timezone.get_default_timezone())
def default_start_date(): d = timezone.localdate() return timezone.datetime(d.year, d.month, d.day, 8, 0, 0, tzinfo=timezone.utc)
def is_in_subscription_date(self, date=timezone.localdate()): return not self.is_canceled and self.date_start <= date <= self.date_end
def migrate_state(self, user_model, entity_slug: str, force_migrate: bool = False, commit: bool = True, je_date: date = None): if self.migrate_allowed() or force_migrate: txs_digest = self.ledger.digest(user_model=user_model, process_groups=False, process_roles=False, process_ratios=False) account_data = txs_digest['tx_digest']['accounts'] cash_acc_db = next( iter(acc for acc in account_data if acc['account_uuid'] == self.cash_account_id), None) rcv_acc_db = next( iter(acc for acc in account_data if acc['account_uuid'] == self.receivable_account_id), None) pay_acc_db = next( iter(acc for acc in account_data if acc['account_uuid'] == self.payable_account_id), None) earn_acc_db = next( iter(acc for acc in account_data if acc['account_uuid'] == self.earnings_account_id), None) new_state = self.new_state(commit=commit) diff = { 'amount_paid': round( new_state['amount_paid'] - (cash_acc_db['balance'] if cash_acc_db else 0), 2), 'amount_receivable': round( new_state['amount_receivable'] - (rcv_acc_db['balance'] if rcv_acc_db else 0), 2), 'amount_payable': round( new_state['amount_unearned'] - (pay_acc_db['balance'] if pay_acc_db else 0), 2), # todo: chunk this down and figure out a cleaner way to deal with the earnings account. # todo: absolute is used here because amount earned can come from an income account or expense account. 'amount_earned': round( new_state['amount_earned'] - abs(earn_acc_db['balance'] if earn_acc_db else 0), 2) } je_txs = list() # todo: there may be a more efficient way of pulling all missing balance_types al once instead of 1-by-1. if diff['amount_paid'] != 0: if not cash_acc_db: cash_acc_db = self.get_account_bt( account_id=self.cash_account_id, entity_slug=entity_slug, user_model=user_model) cash_tx = { 'account_id': self.cash_account_id, 'tx_type': self.get_tx_type(acc_digest=cash_acc_db, adjustment_amount=diff['amount_paid']), 'amount': abs(diff['amount_paid']), 'description': self.get_migrate_state_desc() } je_txs.append(cash_tx) if diff['amount_receivable'] != 0: if not rcv_acc_db: rcv_acc_db = self.get_account_bt( account_id=self.receivable_account_id, entity_slug=entity_slug, user_model=user_model) receivable_tx = { 'account_id': self.receivable_account_id, 'tx_type': self.get_tx_type( acc_digest=rcv_acc_db, adjustment_amount=diff['amount_receivable']), 'amount': abs(diff['amount_receivable']), 'description': self.get_migrate_state_desc() } je_txs.append(receivable_tx) if diff['amount_payable'] != 0: if not pay_acc_db: pay_acc_db = self.get_account_bt( account_id=self.payable_account_id, entity_slug=entity_slug, user_model=user_model) payable_tx = { 'account_id': self.payable_account_id, 'tx_type': self.get_tx_type(acc_digest=pay_acc_db, adjustment_amount=diff['amount_payable']), 'amount': abs(diff['amount_payable']), 'description': self.get_migrate_state_desc() } je_txs.append(payable_tx) if diff['amount_earned'] != 0: if not earn_acc_db: earn_acc_db = self.get_account_bt( account_id=self.earnings_account_id, entity_slug=entity_slug, user_model=user_model) earnings_tx = { 'account_id': self.earnings_account_id, 'tx_type': self.get_tx_type(acc_digest=earn_acc_db, adjustment_amount=diff['amount_earned']), 'amount': abs(diff['amount_earned']), 'description': self.get_migrate_state_desc() } je_txs.append(earnings_tx) if len(je_txs) > 0: self.ledger.commit_txs( je_date=localdate() if not je_date else je_date, je_txs=je_txs, je_activity='op', je_posted=True, je_desc=self.get_migrate_state_desc()) else: pass
def timezone_today(): """Return the current date in the current time zone.""" if settings.USE_TZ: return timezone.localdate() else: return datetime.date.today()
def due_in_days(self): td = self.due_date - localdate() if td.days < 0: return 0 return td.days
def get_data(request): labels = ['Protein', 'Carbohydrates', 'Fat'] if not request.user.is_authenticated: currFoodItems = FoodItem.objects.filter().order_by('-date_added')[:3] proMacro = 180 fatMacro = 66 carbMacro = 220 userCals = 2200 testUserCalsFromFood = calcRemainCalories(currFoodItems, userCals, proMacro, fatMacro, carbMacro) foodNames = [] foodCalories = [] calsConvert = 0 for items in currFoodItems: foodNames.append(items.name) calsConvert = float(items.calories) foodCalories.append(calsConvert) print(foodNames) print(foodCalories) default_items = [ testUserCalsFromFood['proteinRemain'], testUserCalsFromFood['carbsRemain'], testUserCalsFromFood['fatRemain'] ] totMacros = [proMacro, carbMacro, fatMacro] data = { "labels": labels, "default": default_items, "total_macros": totMacros, "labels2": foodNames, "totalCals": foodCalories } else: profile = request.user.profile macros = dict() macros = macroCalc(float(profile.weight), 'average', float(profile.calories)) #Queries food items only for the current day queryset = FoodItem.objects.filter( date_added__date=timezone.localdate(), user=request.user) foodNames = [] foodCalories = [] calsConvert = 0 for items in queryset: foodNames.append(items.name) calsConvert = float(items.calories) foodCalories.append(calsConvert) #Calculator to calculate the remaining calories left after querying food consumed for the day calsFromFood = calcRemainCalories(queryset, float(profile.calories), macros['protein'], macros['fat'], macros['carbs']) default_items = [ calsFromFood['proteinRemain'], calsFromFood['carbsRemain'], calsFromFood['fatRemain'] ] totMacros = [macros['protein'], macros['carbs'], macros['fat']] data = { "labels": labels, "default": default_items, "total_macros": totMacros, "labels2": foodNames, "totalCals": foodCalories } return JsonResponse(data)
def _default_title(): now = timezone.localdate() branch_name = git_branch() return "{0}/{1} ({2}) Maintenance".format(now.month, now.day, branch_name)