Python django.template.defaultfilters.date() Examples

The following are 30 code examples for showing how to use django.template.defaultfilters.date(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.template.defaultfilters , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: servo_tags.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def relative_date(value):
    if value in ('', None):
        return ''

    current = timezone.now()
    
    if (current - value) > timedelta(days=1):
        return date(value, "SHORT_DATETIME_FORMAT")
        
    return naturaltime(value) 
Example 2
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _validator(self, value):
        """
        Validate the allowed_dates restrictions on the field.
        """
        allowed = self.config.get('allowed_dates', 'AL')
        today = datetime.date.today()
        if allowed == 'AL':
            pass
        elif allowed == 'LT' and value >= today:
            raise forms.ValidationError("The date must be before today.")
        elif allowed == 'LE' and value > today:
            raise forms.ValidationError("The date cannot be in the future.")
        elif allowed == 'GT' and value <= today:
            raise forms.ValidationError("The date must be after today.")
        elif allowed == 'GE' and value < today:
            raise forms.ValidationError("The date cannot be past.") 
Example 3
Project: cadasta-platform   Author: Cadasta   File: test_widgets.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_render(self):
        expected_html = (
            '  <td>'
            '    <div class="media-left">'
            '       <img src="{thumbnail}"'
            '           class="thumb-60">'
            '    </div>'
            '    <div class="media-body resource-text">'
            '       <label for="file"><strong>Resource Name</strong></label>'
            '       <br>file.txt'
            '    </div>'
            '  </td>'
            '  <td class="hidden-xs hidden-sm">txt</td>'
            '  <td class="hidden-xs hidden-sm">'
            '      john<br>'
            '      John Lennon</td>'
            '  <td class="hidden-xs hidden-sm">{updated}</td>'
            '  <td class="hidden-xs hidden-sm">Attached to 1 other entity</td>'
        )
        widget = ResourceWidget(resource=self.resource)
        rendered = widget.render('file', True)
        assert expected_html.format(
            updated=date(self.resource.last_updated, 'N j, Y, P'),
            thumbnail=self.resource.thumbnail
        ) in rendered 
Example 4
Project: credentials   Author: edx   File: html.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def month(value):
    """
    Provides the month from a provided date as a string.

    This is used to work around a bug in the Spanish django month translations.
    See LEARNER-3859 for more details.

    Arguments:
        value (datetime): date to format

    Returns:
        string: A formatted version of the month
    """
    formatted = date(value, 'E')

    language = get_language()
    if language and language.split('-')[0].lower() == 'es':
        return formatted.lower()

    return formatted 
Example 5
Project: pyconkr-2015   Author: pythonkr   File: models.py    License: MIT License 5 votes vote down vote up
def __unicode__(self):
        return _date(self.day, "Y-m-d (D)") 
Example 6
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_entry_field(self, fieldsubmission=None):
        c = forms.DateField(required=self.config['required'],
            label=self.config['label'],
            validators=[self._validator],
            help_text=self.config['help_text'])
        
        c.widget.attrs['class'] = 'date-input' # a JS chunk uses the class to turn on the datepicker.
        
        if fieldsubmission:
            c.initial = fieldsubmission.data['info']

        return c 
Example 7
Project: coursys   Author: sfu-fas   File: other.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _to_text(self, fieldsubmission=None, format=settings.DATE_FORMAT):
        if fieldsubmission.data['info']:
            d = datetime.datetime.strptime(fieldsubmission.data['info'], '%Y-%m-%d').date()
            return escape(defaultfilters.date(d, format))
        else:
            return 'not entered' 
Example 8
Project: freezer-web-ui   Author: openstack   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def timestamp_to_string(ts):
    return django_date(
        datetime.datetime.fromtimestamp(int(ts)),
        'SHORT_DATETIME_FORMAT') 
Example 9
Project: GTDWeb   Author: lanbing510   File: humanize.py    License: GNU General Public License v2.0 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 10
Project: djangoSIGE   Author: thiagopena   File: movimento.py    License: MIT License 5 votes vote down vote up
def format_data_movimento(self):
        return '%s' % date(self.data_movimento, "d/m/Y") 
Example 11
Project: djangoSIGE   Author: thiagopena   File: compras.py    License: MIT License 5 votes vote down vote up
def format_data_emissao(self):
        return '%s' % date(self.data_emissao, "d/m/Y") 
Example 12
Project: djangoSIGE   Author: thiagopena   File: compras.py    License: MIT License 5 votes vote down vote up
def format_data_vencimento(self):
        return '%s' % date(self.data_vencimento, "d/m/Y") 
Example 13
Project: djangoSIGE   Author: thiagopena   File: compras.py    License: MIT License 5 votes vote down vote up
def format_data_entrega(self):
        return '%s' % date(self.data_entrega, "d/m/Y") 
Example 14
Project: djangoSIGE   Author: thiagopena   File: lancamento.py    License: MIT License 5 votes vote down vote up
def format_data_vencimento(self):
        return '%s' % date(self.data_vencimento, "d/m/Y") 
Example 15
Project: djangoSIGE   Author: thiagopena   File: lancamento.py    License: MIT License 5 votes vote down vote up
def format_data_movimento(self):
        return '%s' % date(self.data_movimento, "d/m/Y") 
Example 16
Project: djangoSIGE   Author: thiagopena   File: nota_fiscal.py    License: MIT License 5 votes vote down vote up
def format_data_emissao(self):
        return '%s' % date(self.dhemi.date(), "d/m/Y") 
Example 17
Project: djangoSIGE   Author: thiagopena   File: vendas.py    License: MIT License 5 votes vote down vote up
def format_data_emissao(self):
        return '%s' % date(self.data_emissao, "d/m/Y") 
Example 18
Project: djangoSIGE   Author: thiagopena   File: vendas.py    License: MIT License 5 votes vote down vote up
def format_data_vencimento(self):
        return '%s' % date(self.data_vencimento, "d/m/Y") 
Example 19
Project: djangoSIGE   Author: thiagopena   File: vendas.py    License: MIT License 5 votes vote down vote up
def format_data_entrega(self):
        return '%s' % date(self.data_entrega, "d/m/Y") 
Example 20
Project: bioforum   Author: reBiocoder   File: humanize.py    License: MIT License 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day return representing string. Otherwise, return a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 21
Project: cadasta-platform   Author: Cadasta   File: widgets.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def render(self, name, *args, **kwargs):
        date_format = formats.get_format("DATETIME_FORMAT",
                                         lang=get_language())
        checkbox = super().render(name, *args, **kwargs)
        num_entities = self.resource.num_entities
        return self.html.format(
            name=name,
            resource=self.resource,
            checkbox=checkbox,
            date_updated=date(self.resource.last_updated, date_format),
            attachment_text=self.get_attachment_text(num_entities),
        ) 
Example 22
Project: online-judge   Author: DMOJ   File: contests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(ContestCalendar, self).get_context_data(**kwargs)

        try:
            month = date(self.year, self.month, 1)
        except ValueError:
            raise Http404()
        else:
            context['title'] = _('Contests in %(month)s') % {'month': date_filter(month, _("F Y"))}

        dates = Contest.objects.aggregate(min=Min('start_time'), max=Max('end_time'))
        min_month = (self.today.year, self.today.month)
        if dates['min'] is not None:
            min_month = dates['min'].year, dates['min'].month
        max_month = (self.today.year, self.today.month)
        if dates['max'] is not None:
            max_month = max((dates['max'].year, dates['max'].month), (self.today.year, self.today.month))

        month = (self.year, self.month)
        if month < min_month or month > max_month:
            # 404 is valid because it merely declares the lack of existence, without any reason
            raise Http404()

        context['now'] = timezone.now()
        context['calendar'] = self.get_table()
        context['curr_month'] = date(self.year, self.month, 1)

        if month > min_month:
            context['prev_month'] = date(self.year - (self.month == 1), 12 if self.month == 1 else self.month - 1, 1)
        else:
            context['prev_month'] = None

        if month < max_month:
            context['next_month'] = date(self.year + (self.month == 12), 1 if self.month == 12 else self.month + 1, 1)
        else:
            context['next_month'] = None
        return context 
Example 23
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: humanize.py    License: MIT License 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day return representing string. Otherwise, return a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 24
Project: Spirit   Author: nitely   File: forms.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        now = timezone.localtime(timezone.now())
        self.fields['timezone'].help_text = _('Current time is: %(date)s %(time)s') % {
            'date': defaultfilters.date(now),
            'time': defaultfilters.time(now)} 
Example 25
Project: Spirit   Author: nitely   File: time.py    License: MIT License 5 votes vote down vote up
def shortnaturaltime(value):
    """
    now, 1s, 1m, 1h, 1 Ene, 1 Ene 2012
    """
    tz = utc if is_aware(value) else None
    now = datetime.now(tz)

    if value > now:  # Future
        return '%(delta)s' % {'delta': defaultfilters.date(value, 'j M \'y')}

    delta = now - value

    if delta.days:
        if defaultfilters.date(now, 'y') == defaultfilters.date(value, 'y'):
            return '%(delta)s' % {'delta': defaultfilters.date(value, 'j M')}

        return '%(delta)s' % {'delta': defaultfilters.date(value, 'j M \'y')}

    if not delta.seconds:
        return _('now')

    count = delta.seconds
    if count < 60:
        return _('%(count)ss') % {'count': count}

    count //= 60
    if count < 60:
        return _('%(count)sm') % {'count': count}

    count //= 60
    return _('%(count)sh') % {'count': count} 
Example 26
Project: python   Author: Yeah-Kun   File: humanize.py    License: Apache License 2.0 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 27
Project: openhgsenti   Author: drexly   File: humanize.py    License: Apache License 2.0 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 28
Project: python2017   Author: bpgc-cte   File: humanize.py    License: MIT License 5 votes vote down vote up
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        tzinfo = getattr(value, 'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    today = datetime.now(tzinfo).date()
    delta = value - today
    if delta.days == 0:
        return _('today')
    elif delta.days == 1:
        return _('tomorrow')
    elif delta.days == -1:
        return _('yesterday')
    return defaultfilters.date(value, arg)


# This filter doesn't require expects_localtime=True because it deals properly
# with both naive and aware datetimes. Therefore avoid the cost of conversion. 
Example 29
Project: pyconapac-2016   Author: pythonkr   File: models.py    License: MIT License 5 votes vote down vote up
def __unicode__(self):
        return _date(self.day, "Y-m-d (D)") 
Example 30
Project: pyconkr-2014   Author: pythonkr   File: models.py    License: MIT License 5 votes vote down vote up
def __unicode__(self):
        return _date(self.day, "Y-m-d (D)")