コード例 #1
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
    def full_name(self):
        def ordinal(value):
            try:
                value = int(value)
            except ValueError:
                return value

            if value % 100 // 10 != 1:
                if value % 10 == 1:
                    # Translators: suffix for 1st
                    ordval = "{:d}{}".format((value, ugettext("st")))
                elif value % 10 == 2:
                    # Translators: suffix for 2nd
                    ordval = "{:d}{}".format((value, ugettext("nd")))
                elif value % 10 == 3:
                    # Translators: suffix for 3rd
                    ordval = "{:d}{}".format((value, ugettext("rd")))
                else:
                    # Translators: suffix for 4th
                    ordval = "{:d}{}".format((value, ugettext("th")))
            else:
                # Translators: suffix for 5th
                ordval = "{:d}{}".format((value, ugettext("th")))

            return ordval

        # Translators: Django's date format for QuarterPeriod.full_name()
        return "%(ordinal_quarter)s Quarter %(year)s (%(start)s to %(end)s)".format(
            ordinal_quarter=ordinal(self.quarter),
            year=date_format(self.middle(), ugettext("Y")),
            start=date_format(self.start_on, ugettext("F")),
            end=date_format(self.end_on, ugettext("F Y")))
コード例 #2
0
 def __unicode__(self):
     klasses = [unicode(k) for k in self.klasses.all()]
     if len(klasses) > 1:
         in_klass = _('in the classes')
     else:
         in_klass = _('in the class')
     klass_names = ', '.join(klasses)
     instructions = _('Referring to use of Mainiti Software {in_klass} '
                      '{klasses}, at month {month} of {year}, by the '
                      'company {client}.')
     return instructions.format(in_klass=in_klass,
                                klasses=klass_names,
                                client=self.contract.client,
                                month=date_format(self.ref_date, 'F'),
                                year=date_format(self.ref_date, 'Y'))
コード例 #3
0
ファイル: list.py プロジェクト: mairin/hyperkitty
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(reverse(
                'archives_with_month', kwargs={
                    "mlist_fqdn": mlist_fqdn,
                    'year': today.year,
                    'month': today.month}))

    begin_date, end_date = get_display_dates(year, month, day)
    store = get_store(request)
    mlist = store.get_list(mlist_fqdn)
    threads = store.get_threads(mlist_fqdn, start=begin_date, end=end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        #list_title = date_format(begin_date, settings.DATE_FORMAT)
        list_title = formats.date_format(begin_date) # works with i18n
        no_results_text = "for this day"
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
    }
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #4
0
def instructor_grade_submission(request, course_name, assignment_id,
                                submission_id):
    submission = get_object_or_404(AssignmentSubmission, id=submission_id)

    form = None
    if request.method == "POST":
        form = GradeAssignmentSubmissionForm(instance=submission,
                                             data=request.POST)
        if form.is_valid():
            graded_submission = form.save(commit=False)
            graded_submission.status = 1  #Graded
            graded_submission.save()

            Notification.create_graded_submission_notification(
                request.course, submission.assignment, graded_submission.user)

            graded_data = date_format(graded_submission.date,
                                      "D. N n, Y \\a\\t P")
            return JsonResponse({
                'success': True,
                'score': graded_submission.score,
                'date': graded_data
            })
        else:
            return JsonResponse(form.compile_errors())
    else:
        form = GradeAssignmentSubmissionForm(instance=submission)

    files = submission.files.all()

    return render_to_response("assignments/grade_submission_form.html", {
        'form': form,
        'submission': submission,
        'files': files
    })
コード例 #5
0
def download_adi_journal(request, receipt_date):
    api_session = get_api_session(request)
    try:
        filedata = adi.get_adi_journal_file(api_session,
                                            receipt_date,
                                            user=request.user)
        record_download(api_session, ADI_JOURNAL_LABEL, receipt_date)
    except EmptyFileError as e:
        record_download(api_session, ADI_JOURNAL_LABEL, receipt_date)
        raise e

    filename = settings.ADI_OUTPUT_FILENAME.format(
        initials=request.user.get_initials(), date=date.today())

    response = HttpResponse(
        filedata,
        content_type=
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading ADI journal for %(date)s' % {
            'username': request.user.username,
            'date': date_format(receipt_date, 'Y-m-d'),
        })

    return response
コード例 #6
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
 def name(self):
     # Translators: django date format for accompagning Quarter in Quarter.name()
     drepr = date_format(self.middle(), ugettext("Y"))
     # Translators: Quarter.name() repr using Quarter number and other
     return ugettext("Q%(quarter)s.%(year)s").format(
         year=drepr,
         quarter=self.quarter)
コード例 #7
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
 def name(self):
     try:
         cls = eval("{}Period".format(self.period_type.title()))
         return cls.objects.get(id=self.id).name()
     except:
         # TRANSLATORS: Django date format for Generic .name()
         return date_format(self.middle(), ugettext("c"))
コード例 #8
0
ファイル: models.py プロジェクト: lamperi/raidikalu
 def get_latest_ex_raid_display(self):
     today = timezone.now().date()
     ex_raid_day = self.latest_ex_raid_at.date()
     days_difference = (ex_raid_day - today).days
     weeks = floor(abs(days_difference) / 7)
     if days_difference == 0:
         return 'tänään'
     elif days_difference == 1:
         return 'huomenna'
     elif days_difference == 2:
         return 'ylihuomenna'
     elif 2 < days_difference < 7:
         return '%s päivän päästä' % days_difference
     elif 7 <= days_difference < 12:
         return 'viikon päästä'
     elif days_difference == -1:
         return 'eilen'
     elif days_difference == -2:
         return 'toissapäivänä'
     elif -2 > days_difference > -7:
         return '%s päivää sitten' % abs(days_difference)
     elif -7 >= days_difference > -14:
         return 'viikko sitten'
     elif days_difference <= -14:
         return '%s viikkoa sitten' % weeks
     else:
         return date_format(self.latest_ex_raid_at, 'j.n.Y')
コード例 #9
0
ファイル: mlist.py プロジェクト: softcoder32/hyperkitty
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(
            reverse('hk_archives_with_month',
                    kwargs={
                        "mlist_fqdn": mlist_fqdn,
                        'year': today.year,
                        'month': today.month
                    }))

    try:
        begin_date, end_date = get_display_dates(year, month, day)
    except ValueError:
        # Wrong date format, for example 9999/0/0
        raise Http404("Wrong date format")
    mlist = get_object_or_404(MailingList, name=mlist_fqdn)
    threads = mlist.get_threads_between(begin_date, end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        #list_title = date_format(begin_date, settings.DATE_FORMAT)
        list_title = formats.date_format(begin_date)  # works with i18n
        no_results_text = "for this day"
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
    }
    if day is None:
        extra_context["participants_count"] = \
            mlist.get_participants_count_for_month(int(year), int(month))
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #10
0
ファイル: list.py プロジェクト: olasd/hyperkitty
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(reverse(
                'archives_with_month', kwargs={
                    "mlist_fqdn": mlist_fqdn,
                    'year': today.year,
                    'month': today.month}))

    begin_date, end_date = get_display_dates(year, month, day)
    store = get_store(request)
    mlist = store.get_list(mlist_fqdn)
    threads = store.get_threads(mlist_fqdn, start=begin_date, end=end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        #list_title = date_format(begin_date, settings.DATE_FORMAT)
        list_title = formats.date_format(begin_date) # works with i18n
        no_results_text = "for this day"
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
    }
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #11
0
def download_disbursements(request, receipt_date):
    api_session = get_api_session(request)
    try:
        filedata = disbursements.get_disbursements_file(api_session,
                                                        receipt_date,
                                                        mark_sent=True)
        record_download(api_session, DISBURSEMENTS_LABEL, receipt_date)
    except EmptyFileError as e:
        record_download(api_session, DISBURSEMENTS_LABEL, receipt_date)
        raise e

    filename = settings.DISBURSEMENT_OUTPUT_FILENAME.format(date=receipt_date)

    response = HttpResponse(
        filedata,
        content_type=
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading Disbursements for %(date)s' % {
            'username': request.user.username,
            'date': date_format(receipt_date, 'Y-m-d'),
        })

    return response
コード例 #12
0
ファイル: mlist.py プロジェクト: khushboo9293/hyperkitty
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(reverse(
                'hk_archives_with_month', kwargs={
                    "mlist_fqdn": mlist_fqdn,
                    'year': today.year,
                    'month': today.month}))

    try:
        begin_date, end_date = get_display_dates(year, month, day)
    except ValueError:
        # Wrong date format, for example 9999/0/0
        raise Http404("Wrong date format")
    mlist = get_object_or_404(MailingList, name=mlist_fqdn)
    threads = mlist.get_threads_between(begin_date, end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        #list_title = date_format(begin_date, settings.DATE_FORMAT)
        list_title = formats.date_format(begin_date) # works with i18n
        no_results_text = "for this day"
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
    }
    if day is None:
        extra_context["participants_count"] = \
            mlist.get_participants_count_for_month(int(year), int(month))
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #13
0
    def get_context_data(self, **kwargs):
        context_data = super().get_context_data(**kwargs)
        form = context_data['form']

        prisons = self.get_prisons()
        login_counts = self.get_login_counts(form.cleaned_data['application'])

        login_stats = []
        for nomis_id, prison_name in prisons:
            login_stat = {
                'nomis_id': nomis_id,
                'prison_name': prison_name,
            }
            monthly_counts = []
            for month in self.months:
                month_key = date_format(month, 'Y-m')
                month_count = login_counts[(nomis_id, month_key)]
                login_stat[month_key] = month_count
                monthly_counts.append(month_count)
            login_stat['monthly_counts'] = monthly_counts
            login_stats.append(login_stat)

        ordering, reversed_order = form.get_ordering()
        login_stats = sorted(login_stats,
                             key=lambda s: s[ordering],
                             reverse=reversed_order)

        context_data['opts'] = Login._meta
        context_data['form'] = form
        context_data['login_stats'] = login_stats
        return context_data
コード例 #14
0
ファイル: filters.py プロジェクト: rosix-ru/django-reportapi
    def get_default_value(self, **kwargs):
        if callable(self.default_value):
            value = self.default_value()
        else:
            value = self.default_value

        value = self.time_replace(value)

        cond = getattr(self, 'default_condition', None)

        if cond and cond == 'range':
            if not isinstance(value, (list, tuple)):
                value = date_format(value, '%s' % self.format)
                return (value, value)

        return date_format(value, '%s' % self.format)
    def test_login_counts(self):
        application = Application.objects.create(
            client_id='test-app',
            client_secret='test-app',
            client_type='confidential',
            authorization_grant_type='password',
            name='Test App',
            user=mommy.make(User),
        )
        prison = mommy.make(Prison, nomis_id='ABC')
        user_in_prison = mommy.make(User)
        another_user_in_prison = mommy.make(User)
        mommy.make(PrisonUserMapping, user=user_in_prison, prisons=[prison])
        mommy.make(PrisonUserMapping,
                   user=another_user_in_prison,
                   prisons=[prison])
        user_not_in_prison = mommy.make(User)

        # last month: 3 login in prison
        self.login(user_in_prison, application, (2018, 3, 10))
        self.login(another_user_in_prison, application, (2018, 3, 17))
        self.login(user_in_prison, application, (2018, 3, 28))
        # this month: 2 logins in prison, 1 not linked to a prison
        self.login(user_in_prison, application, (2018, 4, 10))
        self.login(another_user_in_prison, application, (2018, 4, 11))
        self.login(user_not_in_prison, application, (2018, 4, 10))

        now = make_aware(datetime.datetime(2018, 4, 15, 12))
        with mock.patch('mtp_auth.views.timezone.localtime', return_value=now):
            view = LoginStatsView()
            current_month_progress, months = view.current_month_progress, view.months

        # "today" midday is roughly half way through April
        self.assertAlmostEqual(current_month_progress, 0.5, delta=0.02)

        this_month, last_month, *_ = months
        this_month = date_format(this_month, 'Y-m')
        last_month = date_format(last_month, 'Y-m')

        login_counts = view.get_login_counts(application.client_id)

        # expect there to be double by the end of the month
        self.assertEqual(login_counts[(prison.nomis_id, this_month)], 4)
        self.assertEqual(login_counts[(None, this_month)], 2)
        self.assertEqual(login_counts[(prison.nomis_id, last_month)], 3)
        self.assertEqual(login_counts[(None, last_month)], 0)
コード例 #16
0
ファイル: base.py プロジェクト: strogo/djpcms
def nicerepr(val, nd = 3):
    if val is None:
        return sites.settings.DJPCMS_EMPTY_VALUE
    elif isinstance(val,datetime):
        time = val.time()
        if not time:
            return date_format(val.date(),sites.settings.DATE_FORMAT)
        else:
            return date_format(val,sites.settings.DATETIME_FORMAT)
    elif isinstance(val,date):
        return date_format(val,sites.settings.DATE_FORMAT)
    elif isinstance(val,bool):
        return _boolean_icon(val)
    else:
        try:
            return significant_format(val, n = nd)
        except TypeError:
            return val
コード例 #17
0
 def get_value_text(bf):
     f = bf.field
     v = self.cleaned_data.get(bf.name) or f.initial
     if isinstance(f, forms.ChoiceField):
         return dict(f.choices).get(v)
     if isinstance(f, forms.DateField) and v is not None:
         return date_format(v, 'j M Y')
     if isinstance(f, forms.IntegerField) and v is not None:
         return str(v)
     return v or None
コード例 #18
0
ファイル: models.py プロジェクト: acdha/i18n-tutorial-example
    def __unicode__(self):
        if self.birth_date:
            # We'll be nice and use the active L10N format:
            b_date = date_format(settings.DATE_FORMAT, self.birth_date)
        else:
            b_date = pgettext("Birth Date", u"Unknown Date")

        fmt = pgettext("Author Profile", u"{name} ({birth_date})")

        return fmt.format(name=self.name, birth_date=b_date)
コード例 #19
0
ファイル: widgets.py プロジェクト: litchfield/django-notes
 def __init__(self, attrs={}, format=None):
     super(ReminderDateWidget, self).__init__(attrs=attrs)
     choices = [
         ('', '--------'),
         (date.today(), 'Today'),
         (date.today() + timedelta(days=1), 'Tomorrow'),
     ]
     for offset in range(2, 15):
         d = date.today() + timedelta(days=offset)
         choices += [ (d, date_format(d, 'l jS')) ]
     self.choices = choices
コード例 #20
0
ファイル: tests.py プロジェクト: rtpg/tock
 def test_project_timeline_view(self):
     response = self.app.get(reverse('ProjectView', args=[self.project.pk]))
     table = response.html.find('table')
     self.assertEqual(
         [each.text for each in table.find_all('th')[1:]],
         [date_format(each, settings.DATE_FORMAT) for each in self.dates],
     )
     self.assertEqual(
         [each.text for each in table.find_all('td')[1:]],
         [str(float(each.hours_spent)) for each in self.objs],
     )
コード例 #21
0
def download_refund_file(request, receipt_date):
    filename, csvdata = refund.generate_refund_file_for_date(request, receipt_date)
    logger.info(
        'User "%(username)s" is downloading AccessPay file for %(date)s'
        % {"username": request.user.username, "date": date_format(receipt_date, "Y-m-d")}
    )

    response = HttpResponse(csvdata, content_type="text/plain")
    response["Content-Disposition"] = 'attachment; filename="%s"' % filename

    return response
コード例 #22
0
ファイル: tests.py プロジェクト: rtpg/tock
 def test_project_timeline_view(self):
     response = self.app.get(reverse('ProjectView', args=[self.project.pk]))
     table = response.html.find('table')
     self.assertEqual(
         [each.text for each in table.find_all('th')[1:]],
         [date_format(each, settings.DATE_FORMAT) for each in self.dates],
     )
     self.assertEqual(
         [each.text for each in table.find_all('td')[1:]],
         [str(float(each.hours_spent)) for each in self.objs],
     )
コード例 #23
0
def download_bank_statement(request, receipt_date):
    filename, bai2 = statement.generate_bank_statement(request, receipt_date)

    response = HttpResponse(bai2, content_type="application/octet-stream")
    response["Content-Disposition"] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading bank statement file for %(date)s'
        % {"username": request.user.username, "date": date_format(receipt_date, "Y-m-d")}
    )

    return response
コード例 #24
0
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(
            reverse('hk_archives_with_month',
                    kwargs={
                        "mlist_fqdn": mlist_fqdn,
                        'year': today.year,
                        'month': today.month
                    }))

    try:
        begin_date, end_date = get_display_dates(year, month, day)
    except ValueError:
        # Wrong date format, for example 9999/0/0
        raise Http404("Wrong date format")
    mlist = get_object_or_404(MailingList, name=mlist_fqdn)
    threads = mlist.get_threads_between(begin_date, end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        list_title = formats.date_format(begin_date)  # works with i18n
        no_results_text = "for this day"
    # Export button
    export = {
        "url":
        "%s?start=%s&end=%s" % (reverse(
            "hk_list_export_mbox",
            kwargs={
                "mlist_fqdn": mlist.name,
                "filename": "%s-%s" %
                (mlist.name, begin_date.strftime("%Y-%m"))
            }), begin_date.strftime("%Y-%m-%d"),
                                end_date.strftime("%Y-%m-%d")),
        "message":
        _("Download"),
        "title":
        _("This month in gzipped mbox format"),
    }
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
        "export": export,
    }
    if day is None:
        extra_context["participants_count"] = \
            mlist.get_participants_count_for_month(int(year), int(month))
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #25
0
ファイル: jinjaglobals.py プロジェクト: Emilnurg/anas.ru
def date(value, arg, use_l10n=True):
    value = template_localtime(value)
    if value in (None, ''):
        return ''
    if arg is None:
        arg = settings.DATE_FORMAT
    if arg == 'timestamp':
        return str(int(time.mktime(value.timetuple())))
    try:
        return formats.date_format(value, arg, use_l10n=use_l10n)
    except AttributeError:
        try:
            return date_format(value, arg)
        except AttributeError:
            return ''
コード例 #26
0
    def form_valid(self, form):
        """
        If it's an export view, export and redirect to the referral view.
        If it's a simple form view, the form is valid and was submitted,
            redirect to the search results page.
        Else, render the template.
        """
        if self.is_export_view_type():
            attachment_name = 'exported-%s-%s.xlsx' % (
                self.object_list_context_key,
                date_format(timezone.now(), 'Y-m-d'))
            if self.view_type == ViewType.export_email:
                email_export_xlsx(
                    object_type=self.object_list_context_key,
                    user=self.request.user,
                    session=self.request.session,
                    endpoint_path=form.get_object_list_endpoint_path(),
                    filters=form.get_query_data(),
                    export_description=self.get_export_description(form),
                    attachment_name=attachment_name,
                )
                messages.info(
                    self.request,
                    _('The spreadsheet will be emailed to you at %(email)s') %
                    {'email': self.request.user.email})
                return self.redirect_to_referral_url()
            return ObjectListXlsxResponse(
                form.get_complete_object_list(),
                object_type=self.object_list_context_key,
                attachment_name=attachment_name)

        if (SEARCH_FORM_SUBMITTED_INPUT_NAME in self.request.GET
                and self.search_results_view):
            search_results_url = f'{reverse(self.search_results_view)}?{form.query_string}'
            return redirect(search_results_url)

        if self.view_type != ViewType.advanced_search_form:
            object_list = form.get_object_list()
            context = self.get_context_data(form=form)
            if self.redirect_on_single and len(object_list) == 1 and hasattr(
                    self, 'url_for_single_result'):
                return redirect(self.url_for_single_result(object_list[0]))
            context[self.object_list_context_key] = object_list
            # add objects as an alias for generic logic
            context['objects'] = object_list
        else:
            context = self.get_context_data(form=form)
        return render(self.request, self.get_template_names(), context)
コード例 #27
0
def download_adi_journal(request, receipt_date):
    filename, filedata = adi.generate_adi_journal(request, receipt_date)
    file_description = "ADI journal"

    response = HttpResponse(filedata, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response["Content-Disposition"] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading %(file_description)s for %(date)s'
        % {
            "username": request.user.username,
            "file_description": file_description,
            "date": date_format(receipt_date, "Y-m-d"),
        }
    )

    return response
コード例 #28
0
 def _get_value_text(self, bf, f, v):
     if isinstance(f, forms.ChoiceField):
         v = dict(f.choices).get(v)
         if not v:
             return None
         v = str(v)
         capitalisation = self.description_capitalisation.get(bf.name)
         if capitalisation == 'preserve':
             return v
         if capitalisation == 'lowerfirst':
             return v[0].lower() + v[1:]
         return v.lower()
     if isinstance(f, forms.DateField) and v is not None:
         return date_format(v, 'j M Y')
     if isinstance(f, forms.IntegerField) and v is not None:
         return str(v)
     return v or None
コード例 #29
0
ファイル: mlist.py プロジェクト: simonsmiley/hyperkitty
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    if year is None and month is None:
        today = datetime.date.today()
        return redirect(reverse(
                'hk_archives_with_month', kwargs={
                    "mlist_fqdn": mlist_fqdn,
                    'year': today.year,
                    'month': today.month}))

    try:
        begin_date, end_date = get_display_dates(year, month, day)
    except ValueError:
        # Wrong date format, for example 9999/0/0
        raise Http404("Wrong date format")
    mlist = get_object_or_404(MailingList, name=mlist_fqdn)
    threads = mlist.get_threads_between(begin_date, end_date)
    if day is None:
        list_title = date_format(begin_date, "F Y")
        no_results_text = "for this month"
    else:
        #list_title = date_format(begin_date, settings.DATE_FORMAT)
        list_title = formats.date_format(begin_date) # works with i18n
        no_results_text = "for this day"
    # Export button
    export = {
        "url": "%s?start=%s&end=%s" % (
            reverse("hk_list_export_mbox", kwargs={
                    "mlist_fqdn": mlist.name,
                    "filename": "%s-%s" % (
                        mlist.name, begin_date.strftime("%Y-%m"))}),
            begin_date.strftime("%Y-%m-%d"),
            end_date.strftime("%Y-%m-%d")),
        "message": _("Download"),
        "title": _("This month in gzipped mbox format"),
    }
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
        "export": export,
    }
    if day is None:
        extra_context["participants_count"] = \
            mlist.get_participants_count_for_month(int(year), int(month))
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #30
0
    def get_time_category_display(self, now=datetime.datetime.now()):
        category = self.due_date_time_category(now)
        format = None

        if category == "Today":
            format = "P"
        elif category == "Tomorrow":
            format = "P"
        elif category == "This week":
            format = "D, P"
        elif category == "Next week":
            format = "D, M j"
        elif category == "In a couple weeks":
            format = "D, M j"
        elif category == "In a while":
            format = "M j"

        return date_format(self.due_date, format)
コード例 #31
0
def date(value, arg=None):
    """
    Alternative implementation to the built-in `date` template filter which also accepts the
    date string in iso-8601 as passed in by the REST serializers.
    """
    if value in (None, ''):
        return ''
    if not (isinstance(value, datetime) or isinstance(value, datetime_date)):
        value = from_iso8601(value)
    if arg is None:
        arg = settings.DATE_FORMAT
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return date_format(value, arg)
        except AttributeError:
            return ''
コード例 #32
0
ファイル: models.py プロジェクト: alexmerser/Atlas-LMS
	def get_time_category_display(self, now=datetime.datetime.now()):
		category = self.due_date_time_category(now)
		format = None
		
		if category == "Today":
			format = "P"
		elif category == "Tomorrow":
			format = "P"
		elif category == "This week":
			format = "D, P"
		elif category == "Next week":
			format = "D, M j"
		elif category == "In a couple weeks":
			format = "D, M j"
		elif category == "In a while":
			format = "M j"
		
		return date_format(self.due_date, format)
コード例 #33
0
 def _get_value_text(self, bf):
     f = bf.field
     v = self.cleaned_data.get(bf.name) or f.initial
     if isinstance(f, forms.ChoiceField):
         v = dict(f.choices).get(v)
         if not v:
             return None
         v = str(v)
         capitalisation = self.description_capitalisation.get(bf.name)
         if capitalisation == 'preserve':
             return v
         if capitalisation == 'lowerfirst':
             return v[0].lower() + v[1:]
         return v.lower()
     if isinstance(f, forms.DateField) and v is not None:
         return date_format(v, 'j M Y')
     if isinstance(f, forms.IntegerField) and v is not None:
         return str(v)
     return v or None
コード例 #34
0
    def get_login_counts(self, application):
        login_count_query = f"""
            WITH users AS (
              SELECT user_id, COUNT(*) AS login_count
              FROM mtp_auth_login
              WHERE application_id = %(application_id)s
                AND date_trunc('month', created AT TIME ZONE '{settings.TIME_ZONE}') = %(month)s
              GROUP BY user_id
            )
            SELECT prison_id, SUM(login_count)::integer AS login_count
            FROM users
            LEFT OUTER JOIN mtp_auth_prisonusermapping ON mtp_auth_prisonusermapping.user_id = users.user_id
            LEFT OUTER JOIN mtp_auth_prisonusermapping_prisons ON
              mtp_auth_prisonusermapping_prisons.prisonusermapping_id = mtp_auth_prisonusermapping.id
            GROUP BY prison_id
        """
        login_counts = collections.defaultdict(int)
        try:
            application = Application.objects.get(client_id=application)
        except Application.DoesNotExist:
            return login_counts
        for i, month in enumerate(self.months):
            if i == 0:

                def scale_func(count):
                    return int(round(count / self.current_month_progress))
            else:

                def scale_func(count):
                    return count

            with connection.cursor() as cursor:
                cursor.execute(login_count_query, {
                    'application_id': application.id,
                    'month': month.date(),
                })
                for nomis_id, login_count in cursor.fetchall():
                    login_counts[(nomis_id, date_format(
                        month, 'Y-m'))] = scale_func(login_count)
        return login_counts
コード例 #35
0
def download_refund_file(request, receipt_date):
    api_session = get_api_session(request)
    try:
        csvfile = refund.get_refund_file(api_session,
                                         receipt_date,
                                         mark_refunded=True)
        record_download(api_session, ACCESSPAY_LABEL, receipt_date)
    except EmptyFileError as e:
        record_download(api_session, ACCESSPAY_LABEL, receipt_date)
        raise e

    filename = settings.REFUND_OUTPUT_FILENAME.format(date=date.today())

    response = HttpResponse(csvfile, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading AccessPay file for %(date)s' % {
            'username': request.user.username,
            'date': date_format(receipt_date, 'Y-m-d'),
        })

    return response
コード例 #36
0
def download_bank_statement(request, receipt_date):
    api_session = get_api_session(request)
    try:
        bai2file = statement.get_bank_statement_file(api_session, receipt_date)
        record_download(api_session, MT940_STMT_LABEL, receipt_date)
    except EmptyFileError as e:
        record_download(api_session, MT940_STMT_LABEL, receipt_date)
        raise e

    filename = settings.BANK_STMT_OUTPUT_FILENAME.format(
        account_number=settings.BANK_STMT_ACCOUNT_NUMBER, date=receipt_date)

    response = HttpResponse(bai2file, content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    logger.info(
        'User "%(username)s" is downloading bank statement file for %(date)s' %
        {
            'username': request.user.username,
            'date': date_format(receipt_date, 'Y-m-d'),
        })

    return response
コード例 #37
0
ファイル: views.py プロジェクト: alexmerser/Atlas-LMS
def instructor_grade_submission(request, course_name, assignment_id, submission_id):
	submission = get_object_or_404(AssignmentSubmission, id=submission_id)
	
	form = None
	if request.method == "POST":
		form = GradeAssignmentSubmissionForm(instance=submission, data=request.POST)
		if form.is_valid():
			graded_submission = form.save(commit=False)
			graded_submission.status = 1 #Graded
			graded_submission.save()
			
			Notification.create_graded_submission_notification(request.course, submission.assignment, graded_submission.user)
			
			graded_data = date_format(graded_submission.date, "D. N n, Y \\a\\t P")
			return JsonResponse({ 'success': True, 'score': graded_submission.score, 'date': graded_data })
		else:
			return JsonResponse(form.compile_errors())
	else:
		form = GradeAssignmentSubmissionForm(instance=submission)
		
	files = submission.files.all()
					
	return render_to_response("assignments/grade_submission_form.html",
								{ 'form': form, 'submission': submission, 'files': files })
コード例 #38
0
ファイル: Periods.py プロジェクト: yeleman/snisi
 def full_name(self):
     # Translators: Django's date tmpl format for MonthPeriod.full_name()
     return date_format(self.middle(), ugettext("{sd} to {ed} F Y").format(
         sd=self.start_on.day, ed=self.end_on.day))
コード例 #39
0
 def __unicode__(self):
     return u'[{0}] {1}'.format(date_format(self.change_date, 
         'SHORT_DATETIME_FORMAT'), unicode(self.hardware))
コード例 #40
0
def format_datetime(d):
    return date_format(d, 'Y-d-m H:i')
コード例 #41
0
 def __unicode__(self):
     formatted_date = date_format('Y-m-d H:i', self.when)
     return u'[{0}] Transaction of {1} EUR by {2} in {3}'.format(
             formatted_date, self.amount, self.who, self.cashbook.name)
コード例 #42
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
 def name(self):
     # Translators: Django's date format for YearPeriod.name()
     return date_format(self.middle(), ugettext("F"))
コード例 #43
0
 def __init__(self, months, **kwargs):
     self.base_fields['ordering'].choices.extend(
         ((date_format(month, 'Y-m'), date_format(month, 'F'))
          for month in months))
     super().__init__(**kwargs)
コード例 #44
0
ファイル: models.py プロジェクト: django/djangoproject.com
 def __str__(self):
     return "{}, {}".format(
         self.title, date_format(self.date, "F j, Y")
     )
コード例 #45
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
 def full_name(self):
     # Translators: Django's date template format for MonthPeriod.full_name()
     return date_format(self.middle(), ugettext("F Y"))
コード例 #46
0
ファイル: Period.py プロジェクト: yeleman/kurantooro
 def full_name(self):
     # Translators: Week Full name representation: weeknum, start and end
     return ugettext("Week %(weeknum)s (%(start)s to %(end)s)".format(
         weeknum=date_format(self.middle(), ugettext("W")),
         start=date_format(self.start_on, ugettext("d")),
         end=date_format(self.end_on, ugettext("d F Y"))))
コード例 #47
0
def format_dt(dt):
    return date_format(dt, settings.DATETIME_FORMAT)
コード例 #48
0
ファイル: tz_support.py プロジェクト: WAYbetter/waybetter
def format_dt(dt):
    return date_format(dt, settings.DATETIME_FORMAT)
コード例 #49
0
def archives(request, mlist_fqdn, year=None, month=None, day=None):
    """List of threads in MailingList.

    If year & month is None, we return *all* the threads and render a view with
    all the threads of a MailingList.
    """
    mlist = get_object_or_404(MailingList, name=mlist_fqdn)

    if year is None and month is None:
        # If the year and month is None, we set the begin date to the date of
        # the first email and end date to be today.
        end_date = datetime.date.today()
        # Since we don't need any special filtering, just return *all* the
        # threads ordered by date_active.
        threads = mlist.threads.order_by("-date_active")
        if threads:
            begin_date = Email.objects.order_by('date').first().date
        else:
            begin_date = end_date
        # Set the month and year to be today's.
        year = end_date.year
        month = end_date.month
        # The list title for all the threads.
        list_title = ""
        no_results_text = "for this MailingList"
    else:
        try:
            begin_date, end_date = get_display_dates(year, month, day)
        except ValueError:
            # Wrong date format, for example 9999/0/0
            raise Http404("Wrong date format")

        threads = mlist.get_threads_between(begin_date, end_date)

        if day is None:
            list_title = date_format(begin_date, "F Y")
            no_results_text = _("for this month")
        else:
            list_title = formats.date_format(begin_date)  # works with i18n
            no_results_text = _("for this day")

    # Export button
    export = {
        "url":
        "%s?start=%s&end=%s" %
        (reverse("hk_list_export_mbox",
                 kwargs={
                     "mlist_fqdn": mlist.name,
                     "filename": "%s-%s" %
                     (mlist.name, end_date.strftime("%Y-%m"))
                 }), begin_date.strftime("%Y-%m-%d"),
         end_date.strftime("%Y-%m-%d")),
        "message":
        _("Download"),
        "title":
        _("This month in gzipped mbox format"),
    }
    extra_context = {
        'month': begin_date,
        'month_num': begin_date.month,
        "list_title": list_title.capitalize(),
        "no_results_text": no_results_text,
        "export": export,
    }
    if day is None:
        extra_context["participants_count"] = \
            mlist.get_participants_count_for_month(int(year), int(month))
    return _thread_list(request, mlist, threads, extra_context=extra_context)
コード例 #50
0
 def time(self):
     if self.created.date() == date.today():
         format = 'g:i A'
     else:
         format = 'g:i A, j M Y'
     return date_format(self.created, format)
コード例 #51
0
ファイル: tasks.py プロジェクト: stephanielamm/foiatracker
def post_new_foia_slack(instance_pk):
    instance = Foia.objects.get(pk=instance_pk)

    # Drop out now if we've already sent a Slack notification or if there
    # aren't any recipients set yet
    if instance.notified is True or instance.recipients.count() == 0:
        return

    slack = get_slack()

    msg = "%s just submitted a records request to %s" % (
        instance.email.sender, instance.recipients_str(),
    )
    foia_edit_url = ''.join((
        'https://datalab.dallasnews.com',
        reverse('foia-edit', kwargs={'pk': instance.pk}),
    ))

    attachments = {
        'title': instance.request_subject,
        'title_link': foia_edit_url,
        'color': '#568C2F',
        'fields': [{
            'title': 'Recipient(s)',
            'value': instance.recipients_str(),
            'short': True
        }, {
            'title': 'Response due',
            'value': date_format(instance.due(), 'N j'),
            'short': True
        }, {
            'title': 'Request',
            'value': instance.email.text[0:50],
            'short': False
        }]
    }

    slack_user, slack_img = get_slack_user(instance.email.sender.email)

    if slack_user:
        team_domain = cache.get('slack_team')

        if team_domain is None:
            team_domain = slack.team.info().body['team']['domain']
            cache.set('slack_team', team_domain, 3600)

        attachments.update(
            author_name=str(instance.email.sender),
            author_icon=slack_img,
            author_link='https://%s.slack.com/team/%s' % (
                team_domain,
                slack_user,
            ),
        )

    slack.chat.post_message(
        settings.FOIATRACKER_SLACK_CHANNEL,
        msg,
        as_user=False,
        icon_emoji=':foiatracker:',
        username='******',
        attachments=[attachments, ],
    )

    # Set our flag so we don't re-notify
    instance.notified = True
    instance.save()
コード例 #52
0
ファイル: models.py プロジェクト: ikemo3/djangoproject.com
 def __str__(self):
     return "{}, {}".format(self.title, date_format(self.date, "F j, Y"))
コード例 #53
0
ファイル: models.py プロジェクト: MechanisM/mirosubs
 def time(self):
     if self.created.date() == date.today():
         format = 'g:i A'
     else:
         format = 'g:i A, j M Y'
     return date_format(self.created, format)           
コード例 #54
0
ファイル: models.py プロジェクト: IsacEkberg/crag-finder
def _image_file_path(instance, filename):
    """Returns the subfolder in which to upload images for articles. This results in media/article/img/<filename>"""
    return os.path.join(
        'images', "{:}_{:}".format(date_format(timezone.now(), 'U'), filename))
コード例 #55
0
ファイル: ReportingPeriods.py プロジェクト: yeleman/snisi
 def full_name(self):
     # Translators: Django's date tmpl format for MonthPeriod.full_name()
     return ugettext("W5/ERP {}").format(date_format(
         self.middle(), ugettext("F Y")))
コード例 #56
0
ファイル: models.py プロジェクト: IsacEkberg/crag-finder
def _image_file_path(instance, filename):
    """Returns the subfolder in which to upload images for articles. This results in media/article/img/<filename>"""
    return os.path.join(
        'images', "{:}_{:}".format(date_format(timezone.now(), 'U'), filename)
    )