def admin_formfield_callback(self, field, **kwargs): f = field.formfield(**kwargs) if f: if field.custom_attrs.widget_attrs: f.widget.attrs.update(field.custom_attrs.widget_attrs) if f.help_text: f.widget.attrs.setdefault('tooltip', f.help_text) if field.readonly: f.widget.attrs.setdefault('readonly', True) elif isinstance(f, forms.DateField): f.widget.attrs.setdefault('class', 'form-control input-sm form-date-field') f.widget.attrs.setdefault('ui-mask', _('9999-99-99')) elif isinstance(f, forms.DecimalField): f.widget.attrs['type'] = 'text' f.widget.attrs['ui-money'] = 'ui-money' f.widget.attrs['ui-money-thousands'] = formats.get_format('THOUSAND_SEPARATOR') f.widget.attrs['ui-money-decimal'] = formats.get_format('DECIMAL_SEPARATOR') f.widget.attrs['ui-money-negative'] = True f.widget.attrs.setdefault('class', 'form-control input-sm form-decimal-field') elif isinstance(f, forms.IntegerField): f.widget.attrs.setdefault('class', 'form-control input-sm form-int-field') elif isinstance(f, forms.CharField) and f.max_length and f.max_length <= 5: f.widget.attrs.setdefault('class', 'form-control input-sm form-5c-field') elif isinstance(f, forms.CharField) and f.max_length and f.max_length <= 15: f.widget.attrs.setdefault('class', 'form-control input-sm form-small-field') elif isinstance(f, forms.CharField) and f.max_length and f.max_length <= 20: f.widget.attrs.setdefault('class', 'form-control input-sm form-20c-field') elif isinstance(f.widget, forms.Textarea): f.widget.attrs.setdefault('style', 'resize: none; height: 70px;') f.widget.attrs.setdefault('class', 'form-control input-sm form-long-field') elif isinstance(f, forms.CharField): f.widget.attrs.setdefault('class', 'form-control input-sm form-long-field') return f
def sanitize_separators(value): """ Sanitizes a value according to the current decimal and thousand separator setting. Used with form field input. """ if settings.USE_L10N and isinstance(value, six.string_types): parts = [] decimal_separator = get_format('DECIMAL_SEPARATOR') if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format('THOUSAND_SEPARATOR') if thousand_sep == '.' and value.count('.') == 1 and \ len(value.split('.')[-1]) != 3: # Special case where we suspect a dot meant decimal separator # (see #22171) pass else: for replacement in set([ thousand_sep, unicodedata.normalize('NFKD', thousand_sep)]): value = value.replace(replacement, '') parts.append(value) value = '.'.join(reversed(parts)) return value
def display_for_field(value, field): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return _boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateField) or isinstance(field, models.TimeField): if value: date_format = formats.get_format('DATE_FORMAT') datetime_format = formats.get_format('DATETIME_FORMAT') time_format = formats.get_format('TIME_FORMAT') if isinstance(field, models.DateTimeField): return capfirst(dateformat.format(value, datetime_format)) elif isinstance(field, models.TimeField): return capfirst(dateformat.time_format(value, time_format)) else: return capfirst(dateformat.format(value, date_format)) else: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DecimalField): if value is not None: return ('%%.%sf' % field.decimal_places) % value else: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.FloatField): return escape(value) else: return smart_str(value)
def set_datetime_12_hour_format(lang_code, use_l10n): from django.utils.formats import get_format, _format_cache get_format('DATETIME_INPUT_FORMATS', lang_code, use_l10n) for key in _format_cache: if key[0] == 'DATETIME_INPUT_FORMATS': _format_cache[key] += ('%m/%d/%Y %I:%M %p',)
def render(self, name, value, attrs=None): format = self.format if hasattr(self, 'manual_format'): # For django <= 1.6.5, see # https://code.djangoproject.com/ticket/21173 if self.is_localized and not self.manual_format: format = force_text( formats.get_format('DATETIME_INPUT_FORMATS')[0]) else: # For django >= 1.7 format = format or formats.get_format(self.format_key)[0] input = super(DateTimePickerInput, self).render(name, value, attrs) attrs = {'data-oscarWidget': 'datetime', 'data-datetimeFormat': datetime_format_to_js_datetime_format(format), } div = format_html('<div class="input-append date"{}>', flatatt(attrs)) return mark_safe('{div}' ' {input}' ' <span class="add-on">' ' <i class="icon-calendar"></i>' ' </span>' '</div>' .format(div=div, input=input))
def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ settings.USE_L10N = False activate('ca') try: self.assertEqual('N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual('.', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'10:15 a.m.', time_format(self.t)) self.assertEqual(u'des. 31, 2009', date_format(self.d)) self.assertEqual(u'desembre 2009', date_format(self.d, 'YEAR_MONTH_FORMAT')) self.assertEqual(u'12/31/2009 8:50 p.m.', date_format(self.dt, 'SHORT_DATETIME_FORMAT')) self.assertEqual('No localizable', localize('No localizable')) self.assertEqual(decimal.Decimal('66666.666'), localize(self.n)) self.assertEqual(99999.999, localize(self.f)) self.assertEqual(datetime.date(2009, 12, 31), localize(self.d)) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), localize(self.dt)) self.assertEqual(u'66666.666', Template('{{ n }}').render(self.ctxt)) self.assertEqual(u'99999.999', Template('{{ f }}').render(self.ctxt)) self.assertEqual(u'2009-12-31', Template('{{ d }}').render(self.ctxt)) self.assertEqual(u'2009-12-31 20:50:00', Template('{{ dt }}').render(self.ctxt)) self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual(u'10:15 a.m.', Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009', Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual(u'12/31/2009 8:50 p.m.', Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt)) form = I18nForm({ 'decimal_field': u'66666,666', 'float_field': u'99999,999', 'date_field': u'31/12/2009', 'datetime_field': u'31/12/2009 20:50', 'time_field': u'20:50', 'integer_field': u'1.234', }) self.assertEqual(False, form.is_valid()) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['float_field']) self.assertEqual([u'Introdu\xefu un n\xfamero.'], form.errors['decimal_field']) self.assertEqual([u'Introdu\xefu una data v\xe0lida.'], form.errors['date_field']) self.assertEqual([u'Introdu\xefu una data/hora v\xe0lides.'], form.errors['datetime_field']) self.assertEqual([u'Introdu\xefu un n\xfamero sencer.'], form.errors['integer_field']) form2 = SelectDateForm({ 'date_field_month': u'12', 'date_field_day': u'31', 'date_field_year': u'2009' }) self.assertEqual(True, form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data['date_field']) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31)) ) finally: deactivate()
def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ settings.USE_L10N = False activate("ca") try: self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual(u"10:15 a.m.", time_format(self.t)) self.assertEqual(u"des. 31, 2009", date_format(self.d)) self.assertEqual(u"desembre 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual(u"12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT")) self.assertEqual("No localizable", localize("No localizable")) self.assertEqual(decimal.Decimal("66666.666"), localize(self.n)) self.assertEqual(99999.999, localize(self.f)) self.assertEqual(datetime.date(2009, 12, 31), localize(self.d)) self.assertEqual(datetime.datetime(2009, 12, 31, 20, 50), localize(self.dt)) self.assertEqual(u"66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual(u"99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual(u"2009-12-31", Template("{{ d }}").render(self.ctxt)) self.assertEqual(u"2009-12-31 20:50:00", Template("{{ dt }}").render(self.ctxt)) self.assertEqual(u"66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt)) self.assertEqual(u"100000.0", Template("{{ f|floatformat }}").render(self.ctxt)) self.assertEqual(u"10:15 a.m.", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt)) self.assertEqual(u"12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt)) self.assertEqual( u"12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt) ) form = I18nForm( { "decimal_field": u"66666,666", "float_field": u"99999,999", "date_field": u"31/12/2009", "datetime_field": u"31/12/2009 20:50", "time_field": u"20:50", } ) self.assertEqual(False, form.is_valid()) self.assertEqual([u"Introdu\xefu un n\xfamero."], form.errors["float_field"]) self.assertEqual([u"Introdu\xefu un n\xfamero."], form.errors["decimal_field"]) self.assertEqual([u"Introdu\xefu una data v\xe0lida."], form.errors["date_field"]) self.assertEqual([u"Introdu\xefu una data/hora v\xe0lides."], form.errors["datetime_field"]) form2 = SelectDateForm({"date_field_month": u"12", "date_field_day": u"31", "date_field_year": u"2009"}) self.assertEqual(True, form2.is_valid()) self.assertEqual(datetime.date(2009, 12, 31), form2.cleaned_data["date_field"]) self.assertEqual( u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>', SelectDateWidget(years=range(2009, 2019)).render("mydate", datetime.date(2009, 12, 31)), ) finally: deactivate()
def value_from_datadict(self, data, files, name): date_value, time_value = super(JqDateTimeWidget, self).value_from_datadict(data, files, name) if date_value and time_value: datetime_format = "%s %s" % (DATE_FORMAT, TIME_FORMAT) datetime_input_format = "%s %s" % (get_format('DATE_INPUT_FORMATS')[0], get_format('TIME_INPUT_FORMATS')[1]) datetime_string = "%s %s" % (date_value, time_value) try: return datetime.strptime(datetime_string, datetime_format) except ValueError: return None return None
def get_format(self): format = self.format if hasattr(self, 'manual_format'): # For django <= 1.6.5, see # https://code.djangoproject.com/ticket/21173 if self.is_localized and not self.manual_format: format = force_text(formats.get_format(self.format_key)[0]) else: # For django >= 1.7 format = format or formats.get_format(self.format_key)[0] return format
def render(self, name, value, attrs=None, skip_day_field=True): print "Render %s %s" % (name, value) try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = formats.get_format( 'DATE_INPUT_FORMATS')[0] # Python 2.4 compatibility: # v = datetime.datetime.strptime(value, # input_format) # would be clearer, but datetime.strptime was added in # Python 2.5 v = datetime.datetime(*(time.strptime(value, input_format)[0:6])) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = \ [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = dates.MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = formats.get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj' and not self.skip_day_field: output.append(day_html) return safestring.mark_safe(u'\n'.join(output))
def to_python(self, value): """ Validates that the input can be converted to a time. Returns a Python datetime.time object. """ if value in validators.EMPTY_VALUES: return None if isinstance(value, datetime.datetime): return value.time() if isinstance(value, datetime.time): return value if isinstance(value, list): # Input comes from a 2 SplitTimeWidgets, for example. So, it's two # components: start time and end time. if len(value) != 2: raise ValidationError(self.error_messages['invalid']) if value[0] in validators.EMPTY_VALUES and value[1] in \ validators.EMPTY_VALUES: return None start_value = value[0] end_value = value[1] start_time = None end_time = None for format in self.input_formats or formats.get_format(\ 'TIME_INPUT_FORMATS'): try: start_time = datetime.datetime( *time.strptime(start_value, format)[:6] ).time() except ValueError: if start_time: continue else: raise ValidationError(self.error_messages['invalid']) for format in self.input_formats or formats.get_format(\ 'TIME_INPUT_FORMATS'): try: end_time = datetime.datetime( *time.strptime(end_value, format)[:6] ).time() except ValueError: if end_time: continue else: raise ValidationError(self.error_messages['invalid']) return (start_time, end_time)
def translate_date(date, language, date_format='DATE_FORMAT'): """ Converts the provided date object into a string, while translating its value for the given language. Both the format of the date as well as its values (i.e., name of the Month) are translated. If language is Spainish, then the entire date string is returned in lowercase. This is used to work around a bug in the Spanish django month translations. See EDUCATOR-2328 for more details. For example: date = datetime.datetime(2017, 12, 23) date_in_spanish = translate_date(date, 'es') assert date_in_spanish == '23 de deciembre de 2017' """ with override(language): formatted_date = dateformat.format( date, get_format(date_format, lang=language, use_l10n=True), ) if language and language.startswith('es'): formatted_date = formatted_date.lower() return formatted_date
def _has_changed(self, initial, data): try: input_format = get_format("DATE_INPUT_FORMATS")[0] data = datetime_safe.datetime.strptime(data, input_format).date() except (TypeError, ValueError): pass return super(SelectDateWidget, self)._has_changed(initial, data)
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] # Python 2.4 compatibility: # v = datetime.datetime.strptime(value, input_format) # would be clearer, but datetime.strptime was added in # Python 2.5 v = datetime.datetime(*(time.strptime(value, input_format)[0:6])) year_val, month_val = v.year, v.month except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices, none_value=(0, _('Year'))) choices = [(i, '%02d' % i) for i in range(1,13)] month_html = self.create_select(name, self.month_field, value, month_val, choices, none_value=(0, _('Month'))) output = [] for field in _parse_date_fmt(): if field == 'year': output.append(year_html) elif field == 'month': output.append(month_html) return mark_safe(u'\n'.join(output))
def to_python(self, value): """ Validates that the input can be converted to a date. Returns a Python datetime.datetime object. """ if value in validators.EMPTY_VALUES or value == "YYYY-MM-DD": return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value for format in self.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'): try: value = value.strip() valid_date = datetime.date(*time.strptime(value, format)[:3]) except ValueError: continue if format.count('%') == 1: # The user only provided a year. Add one year to their input. if calendar.isleap(valid_date.year): num_days = 366 - 1 else: num_days = 365 - 1 elif format.count('%') == 2: # The user provided a year and a month. Add a month to their input. num_days = monthrange(valid_date.year, valid_date.month)[1] - 1 else: # A full date was provided (for completeness) num_days = 0 return valid_date + datetime.timedelta(days=num_days) raise ValidationError(self.error_messages['invalid'])
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, six.string_types): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(force_str(value), input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass if year_val is None: match = self.date_re.match(value) if match: year_val, month_val, day_val = [int(val) for val in match.groups()] html = {} choices = [(i, i) for i in self.years] html['year'] = self.create_select(name, self.year_field, value, year_val, choices, self.year_none_value) choices = list(self.months.items()) html['month'] = self.create_select(name, self.month_field, value, month_val, choices, self.month_none_value) choices = [(i, i) for i in range(1, 32)] html['day'] = self.create_select(name, self.day_field, value, day_val, choices, self.day_none_value) output = [] for field in self._parse_date_fmt(): output.append(html[field]) return mark_safe('\n'.join(output))
def add_note(request): """ An ajax view for adding notes to the clients in admin. """ if not request.method == 'POST' or not request.is_ajax(): raise Http404 form = ClientNoteForm(request.POST) if not form.is_valid(): if 'datetime' in form.errors: err_msg = _(u'Zadejte prosím platný datum a čas.') elif 'text' in form.errors: err_msg = _(u'Zadejte prosím neprázdný text.') elif 'client' in form.errors: err_msg = _(u'Zadaný klient neexistuje. (Nebyl mezitím smazán?)') return HttpResponse(serialize({'error': err_msg})) client_note = form.save(commit=False) client_note.author = request.user client_note.save() ret = { 'id': client_note.pk, 'author': client_note.author.username, 'datetime_iso': client_note.datetime.isoformat(), 'datetime_formatted': format(client_note.datetime, get_format('DATETIME_FORMAT')), 'text': client_note.text, } return HttpResponse(serialize(ret))
def to_python(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ if value in validators.EMPTY_VALUES: return None if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): return datetime.datetime(value.year, value.month, value.day) if isinstance(value, list): # Input comes from a SplitDateTimeWidget, for example. So, it's two # components: date and time. if len(value) != 2: raise ValidationError(self.error_messages['invalid']) if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES: return None value = '%s %s' % tuple(value) for format in self.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'): try: return datetime.datetime(*time.strptime(value, format)[:6]) except ValueError: continue raise ValidationError(self.error_messages['invalid'])
def render(self, name, value, attrs=None): try: year_val, month_val = value.year, value.month except AttributeError: year_val = month_val = None if isinstance(value, six.string_types): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(force_str(value), input_format) year_val, month_val = v.year, v.month except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = list(six.iteritems(MONTHS)) month_html = self.create_select(name, self.month_field, value, month_val, choices) output = [] for field in _parse_date_fmt(): if field == 'year': output.append(year_html) elif field == 'month': output.append(month_html) return mark_safe('\n'.join(output))
def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( "DATE_FORMAT", "DATETIME_FORMAT", "TIME_FORMAT", "YEAR_MONTH_FORMAT", "MONTH_DAY_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "FIRST_DAY_OF_WEEK", "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ) result = {} for module in [settings] + get_format_modules(reverse=True): for attr in FORMAT_SETTINGS: result[attr] = get_format(attr) formats = {} for k, v in result.items(): if isinstance(v, (six.string_types, int)): formats[k] = smart_text(v) elif isinstance(v, (tuple, list)): formats[k] = [smart_text(value) for value in v] return formats
def _has_changed(self, initial, data): try: input_format = formats.get_format("TIME_INPUT_FORMATS")[0] initial = datetime.datetime.strptime(initial, input_format).time() except (TypeError, ValueError): pass return super(TimeInput, self)._has_changed(self._format_value(initial), data)
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) format = get_format('DATE_FORMAT') escaped = False output = [] for char in format: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'Yy': output.append(year_html) elif char in 'bFMmNn': output.append(month_html) elif char in 'dj': output.append(day_html) return mark_safe(u'\n'.join(output))
def get_timeuntil(self, obj=None): if not obj or not obj.id or not obj.next_run: return '' format = get_format('DATETIME_FORMAT') value = capfirst(dateformat.format(timezone.localtime(obj.next_run), format)) return "%s<br /><span class='mini'>(%s)</span>" \ % (value, obj.get_timeuntil())
def get_formats(): """ Returns all formats strings required for i18n to work """ FORMAT_SETTINGS = ( "DATE_FORMAT", "DATETIME_FORMAT", "TIME_FORMAT", "YEAR_MONTH_FORMAT", "MONTH_DAY_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "FIRST_DAY_OF_WEEK", "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ) result = {} for module in [settings] + get_format_modules(reverse=True): for attr in FORMAT_SETTINGS: result[attr] = get_format(attr) src = [] for k, v in result.items(): if isinstance(v, (six.string_types, int)): src.append("formats['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(smart_text(v)))) elif isinstance(v, (tuple, list)): v = [javascript_quote(smart_text(value)) for value in v] src.append("formats['%s'] = ['%s'];\n" % (javascript_quote(k), "', '".join(v))) return "".join(src)
def __init__(self): """ Retrieve and convert the localized first week day at initialization. """ HTMLCalendar.__init__(self, AMERICAN_TO_EUROPEAN_WEEK_DAYS[ get_format('FIRST_DAY_OF_WEEK')])
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = get_format("DATE_INPUT_FORMATS")[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v in match.groups()] choices = [(i, i) for i in self.years] year_html = self.create_select(name, self.year_field, value, year_val, choices) choices = MONTHS.items() month_html = self.create_select(name, self.month_field, value, month_val, choices) choices = [(i, i) for i in range(1, 32)] day_html = self.create_select(name, self.day_field, value, day_val, choices) output = [] for field in _parse_date_fmt(): if field == "year": output.append(year_html) elif field == "month": output.append(month_html) elif field == "day": output.append(day_html) return mark_safe(u"\n".join(output))
def render(self, name, value, attrs=None): """Extend the output to return a foundation-datepicker.""" # Set a placeholder attribute - this should be the right thing # based on the locale which goes with your browser language # setting - so 'dd/mm/yyyy' for the UK date_format = ( formats.get_format('DATE_INPUT_FORMATS')[0] .replace('%d', 'dd') .replace('%m', 'mm') .replace('%y', 'yy') .replace('%Y', 'yyyy') ) attrs['placeholder'] = _(date_format) # We'll base the format for the date picker on a separate attribute # so that the placeholder can be translated. attrs['datepicker-format'] = date_format # Add a class attribute so that we can generically javascript things attrs['class'] = (attrs.get('class', '') + " fdatepicker").strip() return mark_safe( u'<div class="input-append">' + super(DatePickerWidget, self).render(name, value, attrs) + u'</div>' )
def __init__(self, attrs=None, format=None): attrs = attrs or {} attrs['data-widget-positioning'] = '{"horizontal": "right", "vertical": "bottom"}' attrs['data-format'] = self._moment_format(format or formats.get_format(self.format_key)[0]) if settings.USE_TZ: attrs['data-time-zone'] = timezone.get_current_timezone_name() super(DateTimeMixin, self).__init__(attrs=attrs, format=format)
def render(self, name, value, attrs=None, extra_context={}): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, basestring): if settings.USE_L10N: try: input_format = formats.get_format( 'DATE_INPUT_FORMATS' )[0] v = datetime.datetime.strptime(value, input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = map(int, match.groups()) context = self.get_context(name, value, attrs=attrs, extra_context=extra_context) context['year_choices'] = [(i, i) for i in self.years] context['year_val'] = year_val context['month_choices'] = MONTHS.items() context['month_val'] = month_val context['day_choices'] = [(i, i) for i in range(1, 32)] context['day_val'] = day_val return loader.render_to_string(self.template_name, context)
def render(self, name, value, attrs=None): from django.utils import formats output = [] output.append( """<SCRIPT LANGUAGE="JavaScript" ID="jscal_%(NAME)s"> var cal_%(NAME)s = new CalendarPopup(); cal_%(NAME)s.showYearNavigation(); cal_%(NAME)s.showYearNavigationInput(); </SCRIPT>""" %{ 'NAME': name, }) output.append(super(CalendarWidget, self).render(name, value, attrs)) date_format = formats.get_format('DATE_INPUT_FORMATS')[0] js_date_format = date_format.replace('%d','dd').replace('%m','MM').replace('%Y','yyyy').replace('%y','yy') output.append( """<a href="#" onClick='cal_%(NAME)s.select(document.forms[0].id_%(NAME)s,"%(NAME)s","%(DATE_FORMAT)s"); return false;' name="%(NAME)s" id="%(NAME)s">Show Calendar</a> """ % \ { 'NAME': name, 'DATE_FORMAT': js_date_format, }) return mark_safe(u''.join(output))
def get_dt_format() -> str: """Return the configured format for displaying datetimes in the Django admin views""" return formats.get_format( getattr(settings, "APSCHEDULER_DATETIME_FORMAT", "N j, Y, f:s a"))
def get_datetime_format(): return get_format('DATETIME_INPUT_FORMATS')[0]
def get_time_format(): return get_format('TIME_INPUT_FORMATS')[0]
def _format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0])
def short_date_format(language_code): # request.LANGUAGE_CODE return formats.get_format('SHORT_DATE_FORMAT', lang=language_code)
def handle(self, **options): # Pick up the options now = datetime.now() self.database = options["database"] if self.database not in settings.DATABASES: raise CommandError("No database settings known for '%s'" % self.database) if options["user"]: try: self.user = (User.objects.all().using( self.database).get(username=options["user"])) except Exception: raise CommandError("User '%s' not found" % options["user"]) else: self.user = None timestamp = now.strftime("%Y%m%d%H%M%S") if self.database == DEFAULT_DB_ALIAS: logfile = "importfromfolder-%s.log" % timestamp else: logfile = "importfromfolder_%s-%s.log" % (self.database, timestamp) try: handler = logging.FileHandler(os.path.join(settings.FREPPLE_LOGDIR, logfile), encoding="utf-8") # handler.setFormatter(logging.Formatter(settings.LOGGING['formatters']['simple']['format'])) logger.addHandler(handler) logger.propagate = False except Exception as e: print("%s Failed to open logfile %s: %s" % (datetime.now(), logfile, e)) task = None errors = [0, 0] try: setattr(_thread_locals, "database", self.database) # Initialize the task if options["task"]: try: task = (Task.objects.all().using( self.database).get(pk=options["task"])) except Exception: raise CommandError("Task identifier not found") if (task.started or task.finished or task.status != "Waiting" or task.name not in ("frepple_importfromfolder", "importfromfolder")): raise CommandError("Invalid task identifier") task.status = "0%" task.started = now task.logfile = logfile else: task = Task( name="importfromfolder", submitted=now, started=now, status="0%", user=self.user, logfile=logfile, ) task.processid = os.getpid() task.save(using=self.database) # Choose the right self.delimiter and language self.delimiter = (get_format("DECIMAL_SEPARATOR", settings.LANGUAGE_CODE, True) == "," and ";" or ",") translation.activate(settings.LANGUAGE_CODE) self.SQLrole = settings.DATABASES[self.database].get( "SQL_ROLE", "report_role") # Execute if "FILEUPLOADFOLDER" in settings.DATABASES[ self.database] and os.path.isdir( settings.DATABASES[self.database]["FILEUPLOADFOLDER"]): # Open the logfile logger.info("%s Started importfromfolder\n" % datetime.now().replace(microsecond=0)) all_models = [(ct.model_class(), ct.pk) for ct in ContentType.objects.all() if ct.model_class()] models = [] for ifile in os.listdir( settings.DATABASES[self.database]["FILEUPLOADFOLDER"]): if not ifile.lower().endswith(( ".sql", ".sql.gz", ".csv", ".csv.gz", ".cpy", ".cpy.gz", ".xlsx", )): continue filename0 = ifile.split(".")[0].split(" (")[0] model = None contenttype_id = None for m, ct in all_models: if matchesModelName(filename0, m): model = m contenttype_id = ct break if not model or model in EXCLUDE_FROM_BULK_OPERATIONS: logger.info( "%s Ignoring data in file: %s" % (datetime.now().replace(microsecond=0), ifile)) elif self.user and not self.user.has_perm("%s.%s" % ( model._meta.app_label, get_permission_codename("add", model._meta), )): # Check permissions logger.info( "%s You don't have permissions to add: %s" % (datetime.now().replace(microsecond=0), ifile)) else: deps = set([model]) GridReport.dependent_models(model, deps) models.append((ifile, model, contenttype_id, deps)) # Sort the list of models, based on dependencies between models models = GridReport.sort_models(models) i = 0 cnt = len(models) for ifile, model, contenttype_id, dependencies in models: task.status = str(int(10 + i / cnt * 80)) + "%" task.message = "Processing data file %s" % ifile task.save(using=self.database) i += 1 filetoparse = os.path.join( os.path.abspath(settings.DATABASES[self.database] ["FILEUPLOADFOLDER"]), ifile, ) if ifile.lower().endswith((".sql", ".sql.gz")): logger.info( "%s Started executing SQL statements from file: %s" % (datetime.now().replace(microsecond=0), ifile)) errors[0] += self.executeSQLfile(filetoparse) logger.info( "%s Finished executing SQL statements from file: %s" % (datetime.now().replace(microsecond=0), ifile)) elif ifile.lower().endswith((".cpy", ".cpy.gz")): logger.info( "%s Started uploading copy file: %s" % (datetime.now().replace(microsecond=0), ifile)) errors[0] += self.executeCOPYfile(model, filetoparse) logger.info( "%s Finished uploading copy file: %s" % (datetime.now().replace(microsecond=0), ifile)) elif ifile.lower().endswith(".xlsx"): logger.info( "%s Started processing data in Excel file: %s" % (datetime.now().replace(microsecond=0), ifile)) returnederrors = self.loadExcelfile(model, filetoparse) errors[0] += returnederrors[0] errors[1] += returnederrors[1] logger.info( "%s Finished processing data in file: %s" % (datetime.now().replace(microsecond=0), ifile)) else: logger.info( "%s Started processing data in CSV file: %s" % (datetime.now().replace(microsecond=0), ifile)) returnederrors = self.loadCSVfile(model, filetoparse) errors[0] += returnederrors[0] errors[1] += returnederrors[1] logger.info( "%s Finished processing data in CSV file: %s" % (datetime.now().replace(microsecond=0), ifile)) else: errors[0] += 1 cnt = 0 logger.error("%s Failed, folder does not exist" % datetime.now().replace(microsecond=0)) # Task update if errors[0] > 0: task.status = "Failed" if not cnt: task.message = "Destination folder does not exist" else: task.message = ( "Uploaded %s data files with %s errors and %s warnings" % (cnt, errors[0], errors[1])) else: task.status = "Done" task.message = "Uploaded %s data files with %s warnings" % ( cnt, errors[1], ) task.finished = datetime.now() except KeyboardInterrupt: if task: task.status = "Cancelled" task.message = "Cancelled" logger.info("%s Cancelled\n" % datetime.now().replace(microsecond=0)) except Exception as e: logger.error("%s Failed" % datetime.now().replace(microsecond=0)) if task: task.status = "Failed" task.message = "%s" % e raise e finally: setattr(_thread_locals, "database", None) if task: if errors[0] == 0: task.status = "Done" else: task.status = "Failed" task.processid = None task.finished = datetime.now() task.save(using=self.database) logger.info("%s End of importfromfolder\n" % datetime.now().replace(microsecond=0))
def date_placeholder(): df = date_format or get_format('DATE_INPUT_FORMATS')[0] return now().replace( year=2000, month=12, day=31, hour=18, minute=0, second=0, microsecond=0 ).strftime(df)
from django.utils.translation import pgettext, ungettext, ugettext as _ from misago.utils.strings import slugify # Build date formats formats = { 'DATE_FORMAT': '', 'DATETIME_FORMAT': '', 'TIME_FORMAT': '', 'YEAR_MONTH_FORMAT': '', 'MONTH_DAY_FORMAT': '', 'SHORT_DATE_FORMAT': '', 'SHORT_DATETIME_FORMAT': '', } for key in formats: formats[key] = get_format(key).replace('P', 'g:i a') def date(val, arg=""): if not val: return _("Never") if not arg: arg = formats['DATE_FORMAT'] elif arg in formats: arg = formats[arg] return format(localtime(val), arg) def reldate(val, arg=""): if not val: return _("Never")
def handle(self, *args, **options): # Pick up the options if 'database' in options: self.database = options['database'] or DEFAULT_DB_ALIAS else: self.database = DEFAULT_DB_ALIAS if self.database not in settings.DATABASES: raise CommandError("No database settings known for '%s'" % self.database) if 'user' in options and options['user']: try: self.user = User.objects.all().using( self.database).get(username=options['user']) except: raise CommandError("User '%s' not found" % options['user']) else: self.user = None now = datetime.now() task = None self.logfile = None try: # Initialize the task if 'task' in options and options['task']: try: task = Task.objects.all().using( self.database).get(pk=options['task']) except: raise CommandError("Task identifier not found") if task.started or task.finished or task.status != "Waiting" or task.name != 'import from folder': raise CommandError("Invalid task identifier") task.status = '0%' task.started = now else: task = Task(name='import from folder', submitted=now, started=now, status='0%', user=self.user) task.arguments = ' '.join(['"%s"' % i for i in args]) task.save(using=self.database) # Choose the right self.delimiter and language self.delimiter = get_format('DECIMAL_SEPARATOR', settings.LANGUAGE_CODE, True) == ',' and ';' or ',' translation.activate(settings.LANGUAGE_CODE) # Execute errors = 0 if os.path.isdir( settings.DATABASES[self.database]['FILEUPLOADFOLDER']): # Open the logfile self.logfile = open( os.path.join( settings.DATABASES[self.database]['FILEUPLOADFOLDER'], 'importfromfolder.log'), "a") print("%s Started import from folder\n" % datetime.now(), file=self.logfile) all_models = [(ct.model_class(), ct.pk) for ct in ContentType.objects.all() if ct.model_class()] models = [] for ifile in os.listdir( settings.DATABASES[self.database]['FILEUPLOADFOLDER']): if not ifile.endswith('.csv'): continue filename0 = ifile.split('.')[0] model = None contenttype_id = None for m, ct in all_models: if filename0.lower() in ( m._meta.model_name.lower(), m._meta.verbose_name.lower(), m._meta.verbose_name_plural.lower()): model = m contenttype_id = ct print("%s Matched a model to file: %s" % (datetime.now(), ifile), file=self.logfile) break if not model or model in EXCLUDE_FROM_BULK_OPERATIONS: print("%s Ignoring data in file: %s" % (datetime.now(), ifile), file=self.logfile) elif self.user and not self.user.has_perm( '%s.%s' % (model._meta.app_label, get_permission_codename('add', model._meta))): # Check permissions print("%s You don't have permissions to add: %s" % (datetime.now(), ifile), file=self.logfile) else: deps = set([model]) GridReport.dependent_models(model, deps) models.append((ifile, model, contenttype_id, deps)) # Sort the list of models, based on dependencies between models models = GridReport.sort_models(models) i = 0 cnt = len(models) for ifile, model, contenttype_id, dependencies in models: i += 1 print("%s Started processing data in file: %s" % (datetime.now(), ifile), file=self.logfile) filetoparse = os.path.join( os.path.abspath(settings.DATABASES[self.database] ['FILEUPLOADFOLDER']), ifile) errors += self.parseCSVloadfromfolder(model, filetoparse) print("%s Finished processing data in file: %s\n" % (datetime.now(), ifile), file=self.logfile) task.status = str(int(10 + i / cnt * 80)) + '%' task.save(using=self.database) else: errors += 1 cnt = 0 print("%s Failed, folder does not exist" % datetime.now(), file=self.logfile) # Task update if errors: task.status = 'Failed' if not cnt: task.message = "Destination folder does not exist" else: task.message = "Uploaded %s data files with %s errors" % ( cnt, errors) else: task.status = 'Done' task.message = "Uploaded %s data files" % cnt task.finished = datetime.now() except Exception as e: print("%s Failed" % datetime.now(), file=self.logfile) if task: task.status = 'Failed' task.message = '%s' % e raise e finally: if task: if not errors: task.status = '100%' else: task.status = 'Failed' task.finished = datetime.now() task.save(using=self.database) if self.logfile: print('%s End of import from folder\n' % datetime.now(), file=self.logfile) self.logfile.close()
def jet_get_date_format(): return get_format('DATE_INPUT_FORMATS')[0]
def __unicode__(self): return u"%s -> %s, %s" % (self.author, self.client, format(self.datetime, get_format('DATE_FORMAT')))
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Show voucher option if an event is selected and vouchers exist vouchers_exist = self.request.event.cache.get('vouchers_exist') if vouchers_exist is None: vouchers_exist = self.request.event.vouchers.exists() self.request.event.cache.set('vouchers_exist', vouchers_exist) if not self.request.event.has_subevents or self.subevent: # Fetch all items items, display_add_to_cart = get_grouped_items(self.request.event, self.subevent, channel=self.request.sales_channel.identifier) context['itemnum'] = len(items) context['allfree'] = all( item.display_price.gross == Decimal('0.00') for item in items if not item.has_variations ) and all( all( var.display_price.gross == Decimal('0.00') for var in item.available_variations ) for item in items if item.has_variations ) # Regroup those by category context['items_by_category'] = item_group_by_category(items) context['display_add_to_cart'] = display_add_to_cart context['show_vouchers'] = vouchers_exist context['vouchers_exist'] = vouchers_exist else: context['show_vouchers'] = False context['vouchers_exist'] = vouchers_exist context['ev'] = self.subevent or self.request.event context['subevent'] = self.subevent context['cart'] = self.get_cart() context['has_addon_choices'] = get_cart(self.request).filter(item__addons__isnull=False).exists() if self.subevent: context['frontpage_text'] = str(self.subevent.frontpage_text) else: context['frontpage_text'] = str(self.request.event.settings.frontpage_text) context['list_type'] = self.request.GET.get("style", self.request.event.settings.event_list_type) if context['list_type'] not in ("calendar", "week") and self.request.event.subevents.count() > 100: if self.request.event.settings.event_list_type not in ("calendar", "week"): self.request.event.settings.event_list_type = "calendar" context['list_type'] = "calendar" if context['list_type'] == "calendar" and self.request.event.has_subevents: self._set_month_year() tz = pytz.timezone(self.request.event.settings.timezone) _, ndays = calendar.monthrange(self.year, self.month) before = datetime(self.year, self.month, 1, 0, 0, 0, tzinfo=tz) - timedelta(days=1) after = datetime(self.year, self.month, ndays, 0, 0, 0, tzinfo=tz) + timedelta(days=1) context['date'] = date(self.year, self.month, 1) context['before'] = before context['after'] = after ebd = defaultdict(list) add_subevents_for_days( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request), before, after, ebd, set(), self.request.event, kwargs.get('cart_namespace') ) context['show_names'] = ebd.get('_subevents_different_names', False) or sum( len(i) for i in ebd.values() if isinstance(i, list) ) < 2 context['weeks'] = weeks_for_template(ebd, self.year, self.month) context['months'] = [date(self.year, i + 1, 1) for i in range(12)] context['years'] = range(now().year - 2, now().year + 3) elif context['list_type'] == "week" and self.request.event.has_subevents: self._set_week_year() tz = pytz.timezone(self.request.event.settings.timezone) week = isoweek.Week(self.year, self.week) before = datetime( week.monday().year, week.monday().month, week.monday().day, 0, 0, 0, tzinfo=tz ) - timedelta(days=1) after = datetime( week.sunday().year, week.sunday().month, week.sunday().day, 0, 0, 0, tzinfo=tz ) + timedelta(days=1) context['date'] = week.monday() context['before'] = before context['after'] = after ebd = defaultdict(list) add_subevents_for_days( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request), before, after, ebd, set(), self.request.event, kwargs.get('cart_namespace') ) context['show_names'] = ebd.get('_subevents_different_names', False) or sum( len(i) for i in ebd.values() if isinstance(i, list) ) < 2 context['days'] = days_for_template(ebd, week) context['weeks'] = [date(self.year, i + 1, 1) for i in range(12)] context['weeks'] = [i + 1 for i in range(53)] context['years'] = range(now().year - 2, now().year + 3) context['week_format'] = get_format('WEEK_FORMAT') if context['week_format'] == 'WEEK_FORMAT': context['week_format'] = WEEK_FORMAT elif self.request.event.has_subevents: context['subevent_list'] = self.request.event.subevents_sorted( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request) ) context['show_cart'] = ( context['cart']['positions'] and ( self.request.event.has_subevents or self.request.event.presale_is_running ) ) if self.request.event.settings.redirect_to_checkout_directly: context['cart_redirect'] = eventreverse(self.request.event, 'presale:event.checkout.start', kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''}) if context['cart_redirect'].startswith('https:'): context['cart_redirect'] = '/' + context['cart_redirect'].split('/', 3)[3] else: context['cart_redirect'] = self.request.path return context
def __init__(self): """Retrieve and convert the localized first week day at initialization""" HTMLCalendar.__init__(self, AMERICAN_TO_EUROPEAN_WEEK_DAYS[ get_format('FIRST_DAY_OF_WEEK')])
def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS")
def time_placeholder(): tf = time_format or get_format('TIME_INPUT_FORMATS')[0] return now().replace( year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ).strftime(tf)
def getFirstDayOfWeek(): return getattr(settings, "JOYOUS_FIRST_DAY_OF_WEEK", get_format("FIRST_DAY_OF_WEEK"))
def get_format(self): format = get_format(self.format_name)[0] for py, js in DATE_FORMAT_PY_JS_MAPPING.iteritems(): format = format.replace(py, js) return format
def get_format(self): return self.format or formats.get_format(self.format_key)[0]
def get_all_format(format_type, lang=None, use_l10n=None): return ['iso8601'] + get_format(format_type, lang, use_l10n)
def test_regex_search_on_products_api_endpoint(self, browser, liveserver): """ test regular expression search on API """ self.api_helper.drop_all_data(liveserver) # API responds always in UTC timezone today_string = DateFormat(datetime.utcnow()).format( get_format("Y-m-d")) self.api_helper.create_product(liveserver, product_id="WS-C2960+24TC-LS", vendor_id=1) first_product = self.api_helper.create_product( liveserver, product_id="WS-C2960-24TC-L", vendor_id=1) second_product = self.api_helper.create_product( liveserver, product_id="WS-C2960+24TC-L", vendor_id=1) self.api_helper.create_product(liveserver, product_id="WS-C2960+24TC-S", vendor_id=1) expected_result = { "pagination": { "last_page": 1, "page": 1, "page_records": 2, "total_records": 2, "url": { "previous": None, "next": None } }, "data": [{ "id": first_product["id"], "product_id": "WS-C2960-24TC-L", "description": "", "list_price": None, "currency": "USD", "tags": "", "vendor": 1, "product_group": None, "url": "https://127.0.0.1:27443/productdb/api/v1/products/%d/" % first_product["id"], "eox_update_time_stamp": None, "end_of_sale_date": None, "end_of_support_date": None, "eol_ext_announcement_date": None, "end_of_sw_maintenance_date": None, "end_of_routine_failure_analysis": None, "end_of_service_contract_renewal": None, "end_of_new_service_attachment_date": None, "end_of_sec_vuln_supp_date": None, "eol_reference_number": None, "eol_reference_url": None, "lc_state_sync": False, "internal_product_id": None, "update_timestamp": today_string, "list_price_timestamp": None }, { "id": second_product["id"], "product_id": "WS-C2960+24TC-L", "description": "", "list_price": None, "currency": "USD", "tags": "", "vendor": 1, "product_group": None, "url": "https://127.0.0.1:27443/productdb/api/v1/products/%d/" % second_product["id"], "eox_update_time_stamp": None, "end_of_sale_date": None, "end_of_support_date": None, "eol_ext_announcement_date": None, "end_of_sw_maintenance_date": None, "end_of_routine_failure_analysis": None, "end_of_service_contract_renewal": None, "end_of_new_service_attachment_date": None, "end_of_sec_vuln_supp_date": None, "eol_reference_number": None, "eol_reference_url": None, "lc_state_sync": False, "internal_product_id": None, "update_timestamp": today_string, "list_price_timestamp": None }] } # escape string according https://www.ietf.org/rfc/rfc2396.txt search_regex = parse.quote_plus("^WS-C2960\+24TC-L$|^WS-C2960-24TC-L$") assert search_regex == "%5EWS-C2960%5C%2B24TC-L%24%7C%5EWS-C2960-24TC-L%24" response = requests.get(liveserver + PRODUCTS_API_ENDPOINT + "?search=" + search_regex, auth=HTTPBasicAuth("pdb_admin", "pdb_admin"), headers={'Content-Type': 'application/json'}, verify=False, timeout=10) assert response.ok is True, response.status_code data = response.json() assert data == expected_result
def __init__(self, *args, **kwargs): # '%H:%M' time_format = get_format('TIME_INPUT_FORMATS')[2] kwargs['time_format'] = time_format return super(SplitDateTimeWidgetNoSecond, self).__init__(*args, **kwargs)
def project_settings(request): """ Adds utility project url and ikwen base url context variable to the context. """ key = 'project_settings' settings_var = cache.get(key) if settings_var: return settings_var console_uri = reverse('ikwen:console') if not getattr(settings, 'IS_IKWEN', False): console_uri = console_uri.replace('/ikwen', '') console_uri = console_uri.replace( getattr(settings, 'WSGI_SCRIPT_ALIAS', ''), '') # DEPRECATED ! agreement_page, legal_mentions_page, about_page defined below is now better agreement_url, legal_mentions_url = None, None try: agreement_url = reverse('flatpage', args=(FlatPage.AGREEMENT, )) except NoReverseMatch: pass try: legal_mentions_url = reverse('flatpage', args=(FlatPage.LEGAL_MENTIONS, )) except NoReverseMatch: pass agreement_page, legal_mentions_page, about_page = None, None, None try: agreement_page = FlatPage.objects.get(url=FlatPage.AGREEMENT).to_dict() except: pass try: legal_mentions_page = FlatPage.objects.get( url=FlatPage.LEGAL_MENTIONS).to_dict() except: pass try: about_page = FlatPage.objects.get(url='about').to_dict() except: pass service = Service.objects.get(pk=getattr(settings, 'IKWEN_SERVICE_ID')) config = service.config lang = translation.get_language() use_l10n = getattr(settings, 'USE_L10N', False) settings_var = { 'settings': { 'DEBUG': getattr(settings, 'DEBUG', False), 'IS_IKWEN': getattr(settings, 'IS_IKWEN', False), 'IS_UMBRELLA': getattr(settings, 'IS_UMBRELLA', False), 'REGISTER_WITH_DOB': getattr(settings, 'REGISTER_WITH_DOB', False), 'IKWEN_SERVICE_ID': getattr(settings, 'IKWEN_SERVICE_ID'), 'IKWEN_BASE_URL': IKWEN_BASE_URL, 'IKWEN_CONSOLE_URL': IKWEN_BASE_URL + console_uri, 'IKWEN_MEDIA_URL': ikwen_settings.MEDIA_URL, 'CLUSTER_MEDIA_URL': ikwen_settings.CLUSTER_MEDIA_URL, 'AGREEMENT_URL': agreement_url, 'LEGAL_MENTIONS_URL': legal_mentions_url, 'PROJECT_URL': getattr(settings, 'PROJECT_URL', ''), 'MEMBER_AVATAR': getattr(settings, 'MEMBER_AVATAR', 'ikwen/img/login-avatar.jpg'), 'DECIMAL_SEPARATOR': get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), 'THOUSAND_SEPARATOR': get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), 'MEMBER_DETAIL_VIEW': getattr(settings, 'MEMBER_DETAIL_VIEW', None) }, 'service': service, 'config': config, 'lang': lang[:2], 'year': datetime.now().year, 'currency_code': config.currency_code, 'currency_symbol': config.currency_symbol, 'agreement_page': agreement_page, 'legal_mentions_page': legal_mentions_page, 'about_page': about_page, } cache_timeout = getattr(settings, 'CACHE_TIMEOUT', 5) cache.set(key, settings_var, cache_timeout * 60) return settings_var
def _subevent_list_context(self): voucher = None if self.request.GET.get('voucher'): try: voucher = Voucher.objects.get(code__iexact=self.request.GET.get('voucher'), event=self.request.event) except Voucher.DoesNotExist: pass context = {} context['list_type'] = self.request.GET.get("style", self.request.event.settings.event_list_type) if context['list_type'] not in ("calendar", "week") and self.request.event.subevents.filter(date_from__gt=now()).count() > 50: if self.request.event.settings.event_list_type not in ("calendar", "week"): self.request.event.settings.event_list_type = "calendar" context['list_type'] = "calendar" if context['list_type'] == "calendar": self._set_month_year() tz = pytz.timezone(self.request.event.settings.timezone) _, ndays = calendar.monthrange(self.year, self.month) before = datetime(self.year, self.month, 1, 0, 0, 0, tzinfo=tz) - timedelta(days=1) after = datetime(self.year, self.month, ndays, 0, 0, 0, tzinfo=tz) + timedelta(days=1) context['date'] = date(self.year, self.month, 1) context['before'] = before context['after'] = after ebd = defaultdict(list) add_subevents_for_days( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request), before, after, ebd, set(), self.request.event, self.kwargs.get('cart_namespace'), voucher, ) # Hide names of subevents in event series where it is always the same. No need to show the name of the museum thousands of times # in the calendar. We previously only looked at the current time range for this condition which caused weird side-effects, so we need # an extra query to look at the entire series. For performance reasons, we have a limit on how many different names we look at. context['show_names'] = sum(len(i) for i in ebd.values() if isinstance(i, list)) < 2 or self.request.event.cache.get_or_set( 'has_different_subevent_names', lambda: len(set(str(n) for n in self.request.event.subevents.order_by().values_list('name', flat=True).annotate(c=Count('*'))[:250])) != 1, timeout=120, ) context['weeks'] = weeks_for_template(ebd, self.year, self.month) context['months'] = [date(self.year, i + 1, 1) for i in range(12)] context['years'] = range(now().year - 2, now().year + 3) elif context['list_type'] == "week": self._set_week_year() tz = pytz.timezone(self.request.event.settings.timezone) week = isoweek.Week(self.year, self.week) before = datetime( week.monday().year, week.monday().month, week.monday().day, 0, 0, 0, tzinfo=tz ) - timedelta(days=1) after = datetime( week.sunday().year, week.sunday().month, week.sunday().day, 0, 0, 0, tzinfo=tz ) + timedelta(days=1) context['date'] = week.monday() context['before'] = before context['after'] = after ebd = defaultdict(list) add_subevents_for_days( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request), before, after, ebd, set(), self.request.event, self.kwargs.get('cart_namespace'), voucher, ) # Hide names of subevents in event series where it is always the same. No need to show the name of the museum thousands of times # in the calendar. We previously only looked at the current time range for this condition which caused weird side-effects, so we need # an extra query to look at the entire series. For performance reasons, we have a limit on how many different names we look at. context['show_names'] = sum(len(i) for i in ebd.values() if isinstance(i, list)) < 2 or self.request.event.cache.get_or_set( 'has_different_subevent_names', lambda: len(set(str(n) for n in self.request.event.subevents.order_by().values_list('name', flat=True).annotate(c=Count('*'))[:250])) != 1, timeout=120, ) context['days'] = days_for_template(ebd, week) years = (self.year - 1, self.year, self.year + 1) weeks = [] for year in years: weeks += [ (date_fromisocalendar(year, i + 1, 1), date_fromisocalendar(year, i + 1, 7)) for i in range(53 if date(year, 12, 31).isocalendar()[1] == 53 else 52) ] context['weeks'] = [[w for w in weeks if w[0].year == year] for year in years] context['week_format'] = get_format('WEEK_FORMAT') if context['week_format'] == 'WEEK_FORMAT': context['week_format'] = WEEK_FORMAT context['short_month_day_format'] = get_format('SHORT_MONTH_DAY_FORMAT') if context['short_month_day_format'] == 'SHORT_MONTH_DAY_FORMAT': context['short_month_day_format'] = SHORT_MONTH_DAY_FORMAT else: context['subevent_list'] = self.request.event.subevents_sorted( filter_qs_by_attr(self.request.event.subevents_annotated(self.request.sales_channel.identifier).using(settings.DATABASE_REPLICA), self.request) ) if self.request.event.settings.event_list_available_only and not voucher: context['subevent_list'] = [ se for se in context['subevent_list'] if not se.presale_has_ended and (se.best_availability_state is None or se.best_availability_state >= Quota.AVAILABILITY_RESERVED) ] return context
def timestampAsStr(stamp, format_='SHORT_DATETIME_FORMAT'): """ Converts a timestamp to date string using specified format (DJANGO format such us SHORT_DATETIME_FORMAT..) """ format_ = formats.get_format(format_) return filters.date(datetime.datetime.fromtimestamp(stamp), format_)
def thousand_separator(): return get_format('THOUSAND_SEPARATOR', get_language())
def render(self, name, value, attrs=None): if not attrs: attrs = {} if 'label' in attrs.keys(): label = attrs.pop('label') else: label = True if self.is_required: attrs.update({"required": "required"}) attrs.update({"class": "form-control ng-valid ng-pristine"}) value_date = '' # str(datetime.today().date()) value_time = '' # '0000' try: list_type = [ str, unicode, ] except NameError: list_type = [ str, ] if value and value != "": if type(value) == datetime: value_date = value.date() value_time = '{0:02d}{1:02d}'.format(value.time().hour, value.time().minute) elif type(value) in list_type: # 2015-06-03 00:00 or 2015-06-03 00:00:00 try: ########################################################################### # WARNING: I suspect this is a bad patch because it doesn't detect the # # format of the data depending on the Django's localization # # system. It should checked how is being used in # # method value_from_datadict() from this same class # ########################################################################### if len(value) == 16: aux = datetime.strptime(value, "%Y-%m-%d %H:%M") elif len(value) == 19: aux = datetime.strptime(value, "%Y-%m-%d %H:%M:%S") else: aux = None except ValueError: aux = None if aux: value_date = aux.date() value_time = '{0:02d}{1:02d}'.format( aux.time().hour, aux.time().minute) startview = 2 minview = 2 maxview = 4 icon = 'calendar' ############################################################################## # WARNING: Language code should be detected on runtime from the user request # ############################################################################## langcode = settings.LANGUAGE_CODE format_date = formats.get_format( 'DATETIME_INPUT_FORMATS', lang=langcode)[0].replace("%", "").replace('d', 'dd').replace( 'm', 'mm').replace('Y', 'yyyy').replace('H', 'hh').replace('M', 'ii').split(" ")[0] language = settings.LANGUAGE_CODE #language = {{LANGUAGE_CODE|default:"en"}} if label: html = '<label style="margin-right:10px" class="pull-right" for="id_date">' + _( 'Hour') + '</label>' else: html = '' html += '<div class="row">' html += '<div class="col-sm-8">' html += ' <div class="dropdown">' html += ' <div id="date_{0}" class="input-group date">'.format(name) attributes = ' '.join( [x + '="' + y + '"' for x, y in attrs.iteritems()]) html += ' <input type="text" name="{0}" id="id_{0}" value="{1}" {2} />'.format( name, value_date, attributes) html += ' <span class="input-group-addon"><i class="glyphicon glyphicon-{0}"></i></span>'.format( icon) html += ' </div>' html += ' </div>' html += '</div>' html += '<div class="col-sm-4">' ngmodel = attrs['ng-model'].split('\']') if len(ngmodel) > 1: ngmodel[0] = "{}_time".format(ngmodel[0]) ngmodel = "']".join(ngmodel) else: ngmodel = attrs['ng-model'] + '_time' #attrs['ng-model'] = attrs['ng-model']+'_time' attrs['ng-model'] = ngmodel attributes = ' '.join( [x + '="' + y + '"' for x, y in attrs.iteritems()]) html += ' <input type="text" name="{0}_time" id="id_{0}_time" value="{1}" maxlength="4" {2} />'.format( name, value_time, attributes) html += '</div>' html += '</div>' html += '<script type="text/javascript"> ' html += '$("#date_{0}").datetimepicker({1}'.format(name, '{') html += ' format: "{0}",'.format(format_date) html += ' autoclose: true,' html += ' language:"{0}",'.format(language) html += ' todayBtn: true,' html += ' weekStart:1,' html += ' todayHighlight:true,' html += ' pickerPosition:"bottom-left",' html += ' keyboardNavigation:false,' html += ' startView:{0},'.format(startview) html += ' minView:{0},'.format(minview) html += ' maxView:{0},'.format(maxview) html += ' minuteStep: 15,' html += '});' html += '</script>' return html
def decimal_separator(): return get_format('DECIMAL_SEPARATOR', get_language())
def first_day_of_week(language_code): # request.LANGUAGE_CODE return formats.get_format('FIRST_DAY_OF_WEEK', lang=language_code)
def _formats(self): return formats.get_format(self.formats_source)
def render_js_init(self, id_, name, value): return 'initDateTimeChooser({0}, {1});'.format( json.dumps(id_), json.dumps({'dayOfWeekStart': get_format('FIRST_DAY_OF_WEEK')}))