Python django.utils.formats.date_format() Examples

The following are 30 code examples of django.utils.formats.date_format(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.formats , or try the search function .
Example #1
Source File: test_user.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_page_subscription_lite_2020(self):
        image = Generators.image()
        image.user = self.user
        image.save()

        us = Generators.premium_subscription(self.user, "AstroBin Lite 2020+")

        self.client.login(username='user', password='password')

        response = self.client.get(reverse('user_page', args=('user',)))

        self.assertContains(response, "<h4>Subscription</h4>", html=True)
        self.assertContains(response, "<strong data-test='subscription-type'>AstroBin Lite</strong>", html=True)
        self.assertContains(
            response,
            "<strong data-test='expiration-date'>" +
            formats.date_format(us.expires, "SHORT_DATE_FORMAT") +
            "</strong>",
            html=True)
        self.assertContains(response, "<strong data-test='images-used'>0 / 123</strong>", html=True)

        self.client.logout()
        us.delete()
        image.delete() 
Example #2
Source File: job.py    From helfertool with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.job = kwargs.pop('job')
        super(JobDuplicateDayForm, self).__init__(*args, **kwargs)

        # get a list of all days where a shifts begins
        day_with_shifts = []
        for shift in self.job.shift_set.all():
            day = shift.date()
            if day not in day_with_shifts:
                day_with_shifts.append(day)

        # and set choices for field
        old_date_choices = []
        for day in sorted(day_with_shifts):
            day_str = str(day)
            day_localized = formats.date_format(day, "SHORT_DATE_FORMAT")
            old_date_choices.append((day_str, day_localized))

        self.fields['old_date'].choices = old_date_choices 
Example #3
Source File: models.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_email(self, form):
        content = []

        cleaned_data = form.cleaned_data
        for field in form:
            if field.name not in cleaned_data:
                continue

            value = cleaned_data.get(field.name)

            if isinstance(value, list):
                value = ', '.join(value)

            # Format dates and datetimes with SHORT_DATE(TIME)_FORMAT
            if isinstance(value, datetime.datetime):
                value = date_format(value, settings.SHORT_DATETIME_FORMAT)
            elif isinstance(value, datetime.date):
                value = date_format(value, settings.SHORT_DATE_FORMAT)

            content.append('{}: {}'.format(field.label, value))

        return '\n'.join(content) 
Example #4
Source File: test_initial_application.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def test_community_landing_approved_after_contribution_opens(self):
        """
        This tests that the initial application results.
        The applicant is approved.
        The round is in the contribution period.
        They should be able to see projects on the community landing page.
        """
        project = self.setup_approved_project_approved_community('contributions_open')

        applicant = factories.ApplicantApprovalFactory(approval_status=models.ApprovalStatus.APPROVED, application_round=project.project_round.participating_round)
        self.client.force_login(applicant.applicant.account)

        response = self.client.get(reverse('community-landing', kwargs={'round_slug': project.project_round.participating_round.slug, 'community_slug': project.project_round.community.slug}))
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response,
                '<p>If you are an Outreachy applicant, this information will be available once the Outreachy contribution period starts on {} at 4pm UTC. You can sign up for an email notification when the round opens by <a href="https://lists.outreachy.org/cgi-bin/mailman/listinfo/announce">subscribing to the Outreachy announcements mailing list</a>.</p>'.format(date_format(project.project_round.participating_round.contributions_open)),
                html=True)
        self.assertContains(response, '<h1>Outreachy Internships with Debian</h1>', html=True)
        self.assertContains(response, '<h1>Open Projects</h1>', html=True)
        self.assertContains(response, '<hr id="{}">'.format(project.slug), html=True)
        self.assertContains(response, '<h2>{}</h2>'.format(project.short_title), html=True)

    # ----- contribution recording page tests ----- # 
Example #5
Source File: test_initial_application.py    From website with GNU General Public License v3.0 6 votes vote down vote up
def test_community_landing_pending_after_contribution_opens(self):
        """
        This tests that the initial application results.
        The applicant is approved.
        The round is in the contribution period.
        They should be able to see projects on the community landing page.
        """
        project = self.setup_approved_project_approved_community('contributions_open')

        applicant = factories.ApplicantApprovalFactory(approval_status=models.ApprovalStatus.PENDING, application_round=project.project_round.participating_round)
        self.client.force_login(applicant.applicant.account)

        response = self.client.get(reverse('community-landing', kwargs={'round_slug': project.project_round.participating_round.slug, 'community_slug': project.project_round.community.slug}))
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response,
                '<p>If you are an Outreachy applicant, this information will be available once the Outreachy contribution period starts on {} at 4pm UTC. You can sign up for an email notification when the round opens by <a href="https://lists.outreachy.org/cgi-bin/mailman/listinfo/announce">subscribing to the Outreachy announcements mailing list</a>.</p>'.format(date_format(project.project_round.participating_round.contributions_open)),
                html=True)
        self.assertNotContains(response, '<h1>Outreachy Internships with Debian</h1>', html=True)
        self.assertNotContains(response, '<h1>Open Projects</h1>', html=True)
        self.assertNotContains(response, '<hr id="{}">'.format(project.slug), html=True)
        self.assertNotContains(response, '<h2>{}</h2>'.format(project.short_title), html=True) 
Example #6
Source File: telltime.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dateShortFormat(when):
    """
    Short version of the date when, e.g. 14 April 2017

    Uses the format given by JOYOUS_DATE_SHORT_FORMAT if that is set, or otherwise
    the standard Django date format.
    """
    retval = ""
    if when is not None:
        formatStr = getattr(settings, 'JOYOUS_DATE_SHORT_FORMAT', None)   # e.g. "j F Y"
        if formatStr:
            retval = _Formatter(when).format(formatStr)
        else:
            retval = formats.date_format(when, "SHORT_DATE_FORMAT")
    return retval.strip()

# ------------------------------------------------------------------------------ 
Example #7
Source File: test_user.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_page_subscription_lite(self):
        image = Generators.image()
        image.user = self.user
        image.save()

        us = Generators.premium_subscription(self.user, "AstroBin Lite")

        self.client.login(username='user', password='password')

        response = self.client.get(reverse('user_page', args=('user',)))

        self.assertContains(response, "<h4>Subscription</h4>", html=True)
        self.assertContains(response, "<strong data-test='subscription-type'>AstroBin Lite</strong>", html=True)
        self.assertContains(
            response,
            "<strong data-test='expiration-date'>" +
            formats.date_format(us.expires, "SHORT_DATE_FORMAT") +
            "</strong>",
            html=True)
        self.assertContains(response, "<strong data-test='images-used'>0 / 123</strong>", html=True)

        self.client.logout()
        us.delete()
        image.delete() 
Example #8
Source File: test_user.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_page_subscription_premium(self):
        image = Generators.image()
        image.user = self.user
        image.save()

        us = Generators.premium_subscription(self.user, "AstroBin Premium")

        self.client.login(username='user', password='password')

        response = self.client.get(reverse('user_page', args=('user',)))

        self.assertContains(response, "<h4>Subscription</h4>", html=True)
        self.assertContains(response, "<strong data-test='subscription-type'>AstroBin Premium</strong>", html=True)
        self.assertContains(
            response,
            "<strong data-test='expiration-date'>" +
            formats.date_format(us.expires, "SHORT_DATE_FORMAT") +
            "</strong>",
            html=True)
        self.assertContains(response, "<strong data-test='images-used'>0 / &infin;</strong>", html=True)

        self.client.logout()
        us.delete()
        image.delete() 
Example #9
Source File: test_user.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_page_subscription_premium_2020(self):
        image = Generators.image()
        image.user = self.user
        image.save()

        us = Generators.premium_subscription(self.user, "AstroBin Premium 2020+")

        self.client.login(username='user', password='password')

        response = self.client.get(reverse('user_page', args=('user',)))

        self.assertContains(response, "<h4>Subscription</h4>", html=True)
        self.assertContains(response, "<strong data-test='subscription-type'>AstroBin Premium</strong>", html=True)
        self.assertContains(
            response,
            "<strong data-test='expiration-date'>" +
            formats.date_format(us.expires, "SHORT_DATE_FORMAT") +
            "</strong>",
            html=True)
        self.assertContains(response, "<strong data-test='images-used'>0 / &infin;</strong>", html=True)

        self.client.logout()
        us.delete()
        image.delete() 
Example #10
Source File: test_user.py    From astrobin with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_page_subscription_ultimate(self):
        image = Generators.image()
        image.user = self.user
        image.save()

        us = Generators.premium_subscription(self.user, "AstroBin Ultimate 2020+")

        self.client.login(username='user', password='password')

        response = self.client.get(reverse('user_page', args=('user',)))

        self.assertContains(response, "<h4>Subscription</h4>", html=True)
        self.assertContains(response, "<strong data-test='subscription-type'>AstroBin Ultimate</strong>", html=True)
        self.assertContains(
            response,
            "<strong data-test='expiration-date'>" +
            formats.date_format(us.expires, "SHORT_DATE_FORMAT") +
            "</strong>",
            html=True)
        self.assertContains(response, "<strong data-test='images-used'>0 / &infin;</strong>", html=True)

        self.client.logout()
        us.delete()
        image.delete() 
Example #11
Source File: utils.py    From django-datatables-view with MIT License 6 votes vote down vote up
def format_datetime(dt, include_time=True):
    """
    Here we adopt the following rule:
    1) format date according to active localization
    2) append time in military format
    """
    if dt is None:
        return ''

    if isinstance(dt, datetime.datetime):
        try:
            dt = timezone.localtime(dt)
        except:
            local_tz = pytz.timezone(getattr(settings, 'TIME_ZONE', 'UTC'))
            dt = local_tz.localize(dt)
    else:
        assert isinstance(dt, datetime.date)
        include_time = False

    use_l10n = getattr(settings, 'USE_L10N', False)
    text = formats.date_format(dt, use_l10n=use_l10n, format='SHORT_DATE_FORMAT')
    if include_time:
        text += dt.strftime(' %H:%M:%S')
    return text 
Example #12
Source File: imapheader.py    From modoboa-webmail with MIT License 6 votes vote down vote up
def parse_date(value, **kwargs):
    """Parse a Date: header."""
    tmp = email.utils.parsedate_tz(value)
    if not tmp:
        return value
    ndate = datetime.datetime.fromtimestamp(email.utils.mktime_tz(tmp))
    if ndate.tzinfo is not None:
        tz = timezone.get_current_timezone()
        ndate = tz.localize(datetime.datetime.fromtimestamp(ndate))
    current_language = get_request().user.language
    if datetime.datetime.now() - ndate > datetime.timedelta(7):
        fmt = "LONG"
    else:
        fmt = "SHORT"
    return date_format(
        ndate,
        DATETIME_FORMATS.get(current_language, DATETIME_FORMATS.get("en"))[fmt]
    ) 
Example #13
Source File: defaultfilters.py    From python2017 with MIT License 5 votes vote down vote up
def date(value, arg=None):
    """Formats a date according to the given format."""
    if value in (None, ''):
        return ''
    try:
        return formats.date_format(value, arg)
    except AttributeError:
        try:
            return format(value, arg)
        except AttributeError:
            return '' 
Example #14
Source File: test_stringifier.py    From django_audit_trail with Apache License 2.0 5 votes vote down vote up
def test_datetime_field(self):
        now = datetime.datetime.now()
        tsm = TestStringifierModel(datetime=now)
        self.assertEqual(ModelFieldStringifier.stringify(self.get_field('datetime'), tsm.datetime),
                         formats.date_format(now, "DATETIME_FORMAT")) 
Example #15
Source File: test_stringifier.py    From django_audit_trail with Apache License 2.0 5 votes vote down vote up
def test_date_field(self):
        today = datetime.date.today()
        tsm = TestStringifierModel(date=today)
        self.assertEqual(ModelFieldStringifier.stringify(self.get_field('date'), tsm.date),
                         formats.date_format(today, "DATE_FORMAT")) 
Example #16
Source File: utils.py    From django-datatables-view with MIT License 5 votes vote down vote up
def parse_date(formatted_date):
    parsed_date = None
    for date_format in formats.get_format('DATE_INPUT_FORMATS'):
        try:
            parsed_date = datetime.datetime.strptime(formatted_date, date_format)
        except ValueError:
            continue
        else:
            break
    if not parsed_date:
        raise ValueError
    return parsed_date.date() 
Example #17
Source File: stringifier.py    From django_audit_trail with Apache License 2.0 5 votes vote down vote up
def stringify_datetime(value, *args):
        if value is None:
            return None

        # Like models.DateField(default=date.today)
        if hasattr(value, '__call__'):
            value = value()

        return formats.date_format(value, "DATETIME_FORMAT") 
Example #18
Source File: player.py    From hawthorne with GNU Lesser General Public License v3.0 5 votes vote down vote up
def detailed_log_date(request, u, date, *args, **kwargs):
  pages = ServerChat.objects.filter(user=u)\
                            .annotate(created_date=Cast('created_at', DateField()))\
                            .values('created_date')\
                            .distinct()\
                            .order_by('-created_date')

  return HttpResponse(date_format(pages[date - 1]['created_date'],
                                  format='SHORT_DATE_FORMAT',
                                  use_l10n=True)) 
Example #19
Source File: stringifier.py    From django_audit_trail with Apache License 2.0 5 votes vote down vote up
def stringify_date(value, *args):
        if value is None:
            return None

        # Like models.DateField(default=date.today)
        if hasattr(value, '__call__'):
            value = value()

        return formats.date_format(value, "DATE_FORMAT") 
Example #20
Source File: tournament_extras.py    From heltour with MIT License 5 votes vote down vote up
def date_el(datetime, arg=None):
    if not datetime:
        return ''
    return mark_safe('<time datetime="%s">%s</time>' % (
        datetime.isoformat(), formats.date_format(datetime, arg))) 
Example #21
Source File: test_now.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_now02(self):
        output = self.engine.render_to_string('now02')
        self.assertEqual(output, date_format(datetime.now())) 
Example #22
Source File: test_now.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_now04(self):
        output = self.engine.render_to_string('now04')
        self.assertEqual(output, date_format(datetime.now())) 
Example #23
Source File: telltime.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dateFormat(when):
    """
    Format the date when, e.g. Friday 14th of April 2011

    Uses the format given by JOYOUS_DATE_FORMAT if that is set, or otherwise
    the standard Django date format.
    """
    retval = ""
    if when is not None:
        formatStr = getattr(settings, 'JOYOUS_DATE_FORMAT', None)   # e.g. "l jS \\o\\f F X"
        if formatStr:
            retval = _Formatter(when).format(formatStr)
        else:
            retval = formats.date_format(when)
    return retval.strip() 
Example #24
Source File: views.py    From della with MIT License 5 votes vote down vote up
def _get_response(self):
        timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
        data = {
            'text': self.object.text,
            'signature': "{} | {}".format(self.object.sent_by.username,
                                          timestamp),
        }
        return {'status': True, 'data': data} 
Example #25
Source File: helpers.py    From jararaca with GNU General Public License v3.0 5 votes vote down vote up
def date_range_format(dates: list):
    text = ''

    total = len(list(groupby(dates, key=attrgetter('month'))))

    i = -1
    for month, dates_month in groupby(dates, key=attrgetter('month')):
        dates_month = list(dates_month)
        i += 1
        for date in dates_month:
            # middle
            if not date == dates_month[0] and not date == dates_month[-1]:
                text += formats.date_format(date, ', d', True)
            # first
            elif date == dates_month[0] and not date == dates_month[-1]:
                text += formats.date_format(date, 'd', True)
            # last
            elif date == dates_month[-1] and not date == dates_month[0]:
                text += formats.date_format(date, ' \e d \d\e F \d\e Y', True)
            # only
            elif date == dates_month[0] and date == dates_month[0]:
                text += formats.date_format(date, 'd \d\e F \d\e Y', True)
        if i == total - 2:
            text += ' e '
        elif total == 1:
            pass
        elif i < total - 2:
            text += ', '

    return text 
Example #26
Source File: models.py    From jararaca with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        return f'{self.event.name} - {date_format(self.date, format="SHORT_DATE_FORMAT", use_l10n=True)}' 
Example #27
Source File: models.py    From jararaca with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        return f'{self.attendee.name} ({self.event_day.event.name} - ' \
            f'{date_format(self.event_day.date, format="SHORT_DATE_FORMAT", use_l10n=True)})' 
Example #28
Source File: admin.py    From jararaca with GNU General Public License v3.0 5 votes vote down vote up
def eventdaycheck_link(self, obj):
        chk = obj.eventdaycheck_set
        if chk:
            html = ''
            for check in obj.eventdaycheck_set.all():
                changeform_url = reverse(
                    'admin:api_eventdaycheck_change', args=(check.id,)
                )
                html += '<a href="%s">%s</a> ' % (
                    changeform_url, date_format(check.event_day.date, format='SHORT_DATE_FORMAT', use_l10n=True))
            return html
        return u'' 
Example #29
Source File: models.py    From horas with MIT License 5 votes vote down vote up
def get_time_range_string(self):
        tz = get_current_timezone()
        start_datetime = self.datetime.astimezone(tz)

        start_time = start_datetime.time()
        end_time = (start_datetime + timedelta(hours=1)).time()

        start_time_fmt = date_format(start_time, "TIME_FORMAT")
        end_time_fmt = date_format(end_time, "TIME_FORMAT")

        return f"{start_time_fmt} - {end_time_fmt} ({start_datetime.tzname()})"

    # state machine transitions 
Example #30
Source File: test_initial_application.py    From website with GNU General Public License v3.0 5 votes vote down vote up
def test_community_landing_approved_and_pending_before_contribution_opens(self):
        """
        This tests that the initial application results.
        Subtests:
         - The applicant is approved.
         - The applicant is pending.
        The round is in the initial application period.
        They shouldn't be able to see projects on the community landing page.
        """
        project = self.setup_approved_project_approved_community('initial_applications_open')

        for approval_status in [models.ApprovalStatus.APPROVED, models.ApprovalStatus.PENDING, ]:
            with self.subTest(approval_status=approval_status):
                applicant = factories.ApplicantApprovalFactory(approval_status=approval_status, application_round=project.project_round.participating_round)
                self.client.force_login(applicant.applicant.account)

                response = self.client.get(reverse('community-landing', kwargs={'round_slug': project.project_round.participating_round.slug, 'community_slug': project.project_round.community.slug}))
                self.assertEqual(response.status_code, 200)
                self.assertContains(response,
                        '<p>If you are an Outreachy applicant, this information will be available once the Outreachy contribution period starts on {} at 4pm UTC. You can sign up for an email notification when the round opens by <a href="https://lists.outreachy.org/cgi-bin/mailman/listinfo/announce">subscribing to the Outreachy announcements mailing list</a>.</p>'.format(date_format(project.project_round.participating_round.contributions_open)),
                        html=True)
                self.assertNotContains(response, '<h1>Outreachy Internships with Debian</h1>', html=True)
                self.assertNotContains(response, '<h1>Open Projects</h1>', html=True)
                self.assertNotContains(response, '<div class="card border" id="{}">'.format(project.slug), html=True)
                self.assertNotContains(response, '<hr id="{}">'.format(project.slug), html=True)
                self.assertNotContains(response, '<h2>{}</h2>'.format(project.short_title), html=True)