def _add_min_max_value(widget, min_date, max_date): if isinstance(min_date, datetime.date): min_date = formats.localize_input(min_date, widget.format) widget.attrs['data-minDate'] = min_date if isinstance(max_date, datetime.date): max_date = formats.localize_input(max_date, widget.format) widget.attrs['data-maxDate'] = max_date
def _check_is_in_calendar_range(self, date): if date and not self.academic_calendar.start_date <= date.date() <= self.academic_calendar.end_date: info = { "date": formats.localize_input(date.date()), "start_date": formats.localize_input(self.academic_calendar.start_date), "end_date": formats.localize_input(self.academic_calendar.end_date), } raise ValidationError(_('%(date)s must be set within %(start_date)s and %(end_date)s'), params=info)
def oozie_to_django_datetime(dt_string): try: return localize_input(datetime.strptime(dt_string, UTC_TIME_FORMAT)) except ValueError: pass try: return localize_input(datetime.strptime(dt_string, GMT_TIME_FORMAT)) except ValueError: pass return None
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(formats.localize_input(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({ 'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_payed': decimal.Decimal('59.47'), 'products_delivered': 12000, }) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>' ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) settings.USE_THOUSAND_SEPARATOR = True # Checking for the localized "products_delivered" field self.assert_( u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul()) finally: deactivate()
def format_value(self, value): if value is not None: # localize_input() returns str on Python 2. return force_text( formats.localize_input( value, self.format or formats.get_format(self.format_key)[0]))
def render(self, name, value='', attrs={}): # Format input id, value and attributes input_attrs = {**attrs, 'name': name, 'type': self.input_type} if value != '': input_attrs['value'] = force_text( formats.localize_input(value, self.format)) # Escape attributes input_attrs = { key: conditional_escape(val) for key, val in input_attrs.items() } div_attrs = { key: conditional_escape(val) for key, val in self.div_attrs.items() } icon_attrs = { key: conditional_escape(val) for key, val in self.icon_attrs.items() } # Render widget html = self.html_template % dict(div_attrs=flatatt(div_attrs), input_attrs=flatatt(input_attrs), icon_attrs=flatatt(icon_attrs)) js = self.js_template % dict(picker_id=input_attrs.get('id'), options=json_dumps(self.options or {})) return mark_safe(force_text(html + js))
def format_value(self, value): # Copied from forms.Input - makes sure value is rendered properly if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value)
def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def parse_duration_ajax(request): if 'duration' in request.GET: duration_str = " " + request.GET['duration'] + " " d = dict() for match in ['w', 'd','h','m','s']: result = re.search('\s(?P<n>[0-9]*)\s?' + match, duration_str) if result: d[match] = int( result.group('n') ) else: d[match] = 0 duration = datetime.timedelta( weeks = d['w'], days = d['d'], hours = d['h'], minutes = d['m'], seconds = d['s']) return HttpResponse(simplejson.dumps({ 'success': True, 'duration': force_unicode(formats.localize_input(duration)), })) return HttpResponse(simplejson.dumps({ 'success': False, }))
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate("de-at") try: form6 = CompanyForm( { "name": u"acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_payed": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>', ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00") self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"]) settings.USE_THOUSAND_SEPARATOR = True self.assert_(u"12.000" in form6.as_ul()) finally: deactivate()
def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif self.formatter is not None: value = datetime_safe.new_datetime(value) return self.formatter(value, self.format) return value
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({ 'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_payed': decimal.Decimal('59.47'), 'products_delivered': 12000, }) self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>' ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) settings.USE_THOUSAND_SEPARATOR = True # Checking for the localized "products_delivered" field self.assert_(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul()) finally: deactivate()
def format_value(self, value): if value is None: value = '' if self.is_localized: value = formats.localize_input(value) return force_text(value)
def _format_value(self, value): # import ipdb; ipdb.set_trace() if self.is_localized: return formats.localize_input(value) elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == '' or value is None: return None if self.is_localized: return formats.localize_input(value)
def _format_value(self, value): if self.is_localized: value = formats.localize_input(value) if value is None: value = '' return force_text(value)
def _format_value(self, value): # import ipdb; ipdb.set_trace() if self.is_localized: return formats.localize_input(value) elif hasattr(value, "strftime"): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def format_value(self, value): """ 返回在模板中呈现时应该出现的值。 """ if value == '' or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value)
def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == '' or value is None: return None if self.is_localized: return formats.localize_input(value) return force_text(value)
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. if isinstance(value, int) or isinstance(value, long): # Database backends serving different types value = from_timedelta(timedelta(microseconds=value)) final_attrs['value'] = force_unicode(formats.localize_input(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == '' or value is None: return None if isinstance(value, str): return value return formats.localize_input(value.quantize(Decimal('1') / 10 ** self.places))
def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, '4.3500')) with translation.override('fr'), self.settings(USE_L10N=True): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n))
def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, "4.3500")) with translation.override("fr"): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n))
def format_value(self, value): """ Return a value as it should appear when rendered in a template. Missing method of django.forms.widgets.Widget class """ if value == '' or value is None: return None return formats.localize_input(value, self.format)
def test_update(self): self.create_user() response = self.client.post("/users/%d/" % self.user.id, { "username": self.user.username, "first_name": "Zachary", "last_name": "Voase", "email": "*****@*****.**", "password": self.user.password, "last_login": formats.localize_input(datetime.datetime.now()), "date_joined": formats.localize_input(datetime.datetime.now()), }) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], 'http://testserver/users/1/') self.user = models.User.objects.get(id=self.user.id) self.assertEqual(self.user.first_name, "Zachary") self.assertEqual(self.user.last_name, "Voase")
def _test_add_project(self): project_name = "FooBar" organization = Organization.objects.get(pk=1) # Fill in details of new project and click "Continue" self.find('id_name').send_keys(project_name) Select(self.find('id_organization')).select_by_value(organization.pk) self.find('pre-add-project-form').submit() # Wait for "Add project" page to load self.assert_that_element_appears('id_add_project_form-name') # Check that project name and organization are propertly transmitted from pre add project form self.assertEquals( project_name, self.find('id_add_project_form-name').get_attribute('value')) self.assertEquals( organization.pk, self.find('id_add_project_form-organization').get_attribute( 'value')) # Fill in the detail of new project and submit phase_field, budget_field, *foo = organization.templates.all( )[0].dimensions.all() project_phase = "Adding-Project" project_budget = 135151.0 self.find('id_{}_form-value'.format( phase_field.id)).send_keys(project_phase) self.find('id_{}_form-value'.format(budget_field.id)).send_keys( localize_input(project_budget)) self.find('add-project-form').submit() # Wait for "Show project" to load self.assert_that_element_appears('project-dimension-panels') # Check that "Show project" page contains correct information self.assertEquals(project_name, self.find('project-name').text) # TODO: Add search for panel with owningorganization # self.assertEquals(organization_name, self.find('projectparent').text) self.assertEquals(project_phase, self.find('Phase').text) budget = number_format(project_budget, decimal_pos=2) self.assertEquals(budget, self.find('Budget').text) # Check that correct information is loaded to db project = Project.objects.get(name=project_name) self.assertIsInstance(project, Project) self.assertEquals(organization, project.parent) phase_dim, budget_dim, *leftovers = project.dimensions.all() self.assertFalse(leftovers) self.assertIsInstance(phase_dim.dimension_object, TextDimension) self.assertIsInstance(budget_dim.dimension_object, NumberDimension) self.assertEquals(Decimal(project_budget), budget_dim.dimension_object.value) self.assertEquals(project_phase, phase_dim.dimension_object.value)
def test_clean_bad_time_range_longer(self): """ Test an improperly formatted time range (tuple with >2 dates) """ time_range = [ localize_input(to_current_timezone(self.today), DATETIME_INPUT_FORMAT), ] * 4 time_range_str = " - ".join(time_range) with self.assertRaises(ValidationError): self.field.clean(time_range_str)
def test_decimalfield_changed(self): f = DecimalField(max_digits=2, decimal_places=2) d = decimal.Decimal("0.1") self.assertFalse(f.has_changed(d, '0.10')) self.assertTrue(f.has_changed(d, '0.101')) with translation.override('fr'), self.settings(USE_L10N=True): f = DecimalField(max_digits=2, decimal_places=2, localize=True) localized_d = formats.localize_input(d) # -> '0,1' in French self.assertFalse(f.has_changed(d, localized_d))
def test_update(self): self.create_user() response = self.client.post( "/users/%d/" % self.user.id, { "username": self.user.username, "first_name": "Zachary", "last_name": "Voase", "email": "*****@*****.**", "password": self.user.password, "last_login": formats.localize_input(datetime.datetime.now()), "date_joined": formats.localize_input(datetime.datetime.now()), }) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], 'http://testserver/users/1/') self.user = models.User.objects.get(id=self.user.id) self.assertEqual(self.user.first_name, "Zachary") self.assertEqual(self.user.last_name, "Voase")
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. if isinstance(value, int) or isinstance( value, long): # Database backends serving different types value = from_timedelta(timedelta(microseconds=value)) final_attrs['value'] = force_unicode(formats.localize_input(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def staffingDates(n=12, format=None, minDate=None): """Returns a list of n next month as datetime (if format="datetime") or as a list of dict() with short/long(encoded) string date""" staffingDate = minDate or date.today().replace(day=1) dates = [] for i in range(int(n)): if format == "datetime": dates.append(staffingDate) else: dates.append({"value": formats.localize_input(staffingDate), "label": formats.date_format(staffingDate, format="YEAR_MONTH_FORMAT").encode("latin-1"), }) staffingDate = nextMonth(staffingDate) return dates
def staffingDates(n=12, format=None, minDate=None): """Returns a list of n next month as datetime (if format="datetime") or as a list of dict() with short/long(encoded) string date""" staffingDate = minDate or date.today().replace(day=1) dates = [] for i in range(n): if format == "datetime": dates.append(staffingDate) else: dates.append({"value": formats.localize_input(staffingDate), "label": formats.date_format(staffingDate, format="YEAR_MONTH_FORMAT").encode("latin-1"), }) staffingDate = nextMonth(staffingDate) return dates
def render(self, name, value, attrs=None): """ output.append(u'<li>%(cb)s<label%(for)s>%(label)s</label></li>' % {"for": label_for, "label": option_label, "cb": rendered_cb}) """ if value is None: value = u'' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != u'': # Only add the 'value' attribute if a value is non-empty. if isinstance(value, int) or isinstance(value, long): # Database backends serving different types value = timedelta(microseconds=value) # Otherwise, we've got a timedelta already final_attrs['value'] = force_unicode(formats.localize_input(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def get_data(request, model_name): try: result = {'data': [], } model = get_model_by_name(model_name) fields = get_fields_of_model(model) data = model.objects.all() for d in data: pprint(d) new_line = [] for f in fields: n = f.name new_line += [localize_input(d.__getattribute__(n))] result['data'] += [new_line] result['result'] = 'ok' except Exception as e: result = {"result": "error", "error_text": "%s" % e.message} return jsonResponse(result)
def render(self, name, value, attrs=None): """ output.append(u'<li>%(cb)s<label%(for)s>%(label)s</label></li>' % {"for": label_for, "label": option_label, "cb": rendered_cb}) """ if value is None: value = "" final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != "": # Only add the 'value' attribute if a value is non-empty. if isinstance(value, six.integer_types): value = timedelta(microseconds=value) # Otherwise, we've got a timedelta already final_attrs["value"] = force_text(formats.localize_input(value)) return mark_safe("<input%s />" % flatatt(final_attrs))
def render(self, name, value, attrs=None): """ output.append(u'<li>%(cb)s<label%(for)s>%(label)s</label></li>' % {"for": label_for, "label": option_label, "cb": rendered_cb}) """ if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. if isinstance(value, six.integer_types): value = timedelta(microseconds=value) # Otherwise, we've got a timedelta already final_attrs['value'] = force_text(formats.localize_input(value)) return mark_safe('<input%s />' % flatatt(final_attrs))
def render(self, name, value, attrs=None, renderer=None): if value is None: value = '' extra_attrs = dict(self.attrs or {}, type=self.input_type, name=name) final_attrs = self.build_attrs(attrs, extra_attrs) if value != '': # Only add the 'value' attribute if a value is non-empty. if isinstance(value, six.integer_types): value = timedelta(microseconds=value) # Otherwise, we've got a timedelta already if self.to_string_fn: final_attrs['value'] = force_text(self.to_string_fn(value)) else: final_attrs['value'] = force_text( formats.localize_input(value)) return mark_safe('<input%s />' % flatatt(final_attrs))
def test_localized_input(self): """ Tests if form input is correctly localized """ settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({ 'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), }) form6.save() self.assertEqual(True, form6.is_valid()) self.assertEqual( form6.as_ul(), u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>' ) self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00') self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added']) finally: deactivate()
def datepicker_value(bound_field): return formats.localize_input(bound_field.value(), bound_field.field.input_formats[0])
def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0])
def _format_value(self, value): if self.is_localized: return formats.localize_input(value) return value
def _format_value(self, value): if self.is_localized: value = formats.localize_input(value) return force_unicode(value)
def datepicker_value(value, date_format): return formats.localize_input(value, date_format)
def datepicker_value(value, date_format): """Retun localized date value.""" return formats.localize_input(value, date_format)
def _format_value(self, value): if self.is_localized: return formats.localize_input(value) value = [str(e) for e in value] return ','.join(value)
def test_can_modify_organized_event(self, patched_send_notification, patched_geocode): self.client.force_login(self.person.role) response = self.client.get( reverse('edit_event', kwargs={'pk': self.organized_event.pk})) self.assertEqual(response.status_code, status.HTTP_200_OK) response = self.client.post( reverse('edit_event', kwargs={'pk': self.organized_event.pk}), data={ 'name': 'New Name', 'calendar': self.calendar.pk, 'start_time': formats.localize_input( timezone.now() + timezone.timedelta(hours=2), "%d/%m/%Y %H:%M"), 'end_time': formats.localize_input( timezone.now() + timezone.timedelta(hours=4), "%d/%m/%Y %H:%M"), 'contact_name': 'Arthur', 'contact_email': '*****@*****.**', 'contact_phone': '06 06 06 06 06', 'location_name': 'somewhere', 'location_address1': 'over', 'location_zip': 'the', 'location_city': 'rainbow', 'location_country': 'FR', 'description': 'New description', 'notify': 'on', 'as_group': self.group.pk, }) # the form redirects to the event list on success self.assertRedirects(response, reverse('list_events')) # accessing the messages: see https://stackoverflow.com/a/14909727/1122474 messages = list(response.wsgi_request._messages) self.assertEqual(len(messages), 1) self.assertEqual(messages[0].level_tag, 'success') # send_support_group_changed_notification.delay should have been called once, with the pk of the group as # first argument, and the changes as the second patched_send_notification.delay.assert_called_once() args = patched_send_notification.delay.call_args[0] self.assertEqual(args[0], self.organized_event.pk) self.assertCountEqual(args[1], ['contact', 'location', 'timing', 'information']) patched_geocode.delay.assert_called_once() args = patched_geocode.delay.call_args[0] self.assertEqual(args[0], self.organized_event.pk) self.assertIn(self.group, self.organized_event.organizers_groups.all())
def test_can_create_new_event(self, patched_send_event_creation_notification, patched_geocode_event): self.client.force_login(self.person.role) # get create page, it should contain the name of the group the user manage response = self.client.get(reverse('create_event')) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, 'Group name') # post create page response = self.client.post( reverse('create_event'), data={ 'name': 'New Name', 'calendar': self.calendar.pk, 'start_time': formats.localize_input( timezone.now() + timezone.timedelta(hours=2), "%d/%m/%Y %H:%M"), 'end_time': formats.localize_input( timezone.now() + timezone.timedelta(hours=4), "%d/%m/%Y %H:%M"), 'contact_name': 'Arthur', 'contact_email': '*****@*****.**', 'contact_phone': '06 06 06 06 06', 'location_name': 'somewhere', 'location_address1': 'over', 'location_zip': 'the', 'location_city': 'rainbow', 'location_country': 'FR', 'description': 'New description', 'as_group': self.group.pk, }) self.assertEqual(response.status_code, status.HTTP_302_FOUND) try: organizer_config = self.person.organizer_configs.exclude( event=self.organized_event).get() except (OrganizerConfig.DoesNotExist, OrganizerConfig.MultipleObjectsReturned): self.fail('Should have created one organizer config') patched_send_event_creation_notification.delay.assert_called_once() self.assertEqual( patched_send_event_creation_notification.delay.call_args[0], (organizer_config.pk, )) patched_geocode_event.delay.assert_called_once() self.assertEqual(patched_geocode_event.delay.call_args[0], (organizer_config.event.pk, )) event = Event.objects.latest(field_name='created') self.assertEqual(event.name, 'New Name') self.assertIn(self.group, event.organizers_groups.all())
def _format_value(self, value): return formats.localize_input(value, self.format or formats.get_format(self.format_key)[0])
def _format_value(self, value): if self.is_localized: value = formats.localize_input(value) return force_text(value)
def _format_value(self, value): return formats.localize_input( value, formats.get_format('DATE_INPUT_FORMATS')[0], )
def format_value(self, value): if value is not None: # localize_input() returns str on Python 2. return force_text(formats.localize_input(value, self.format or formats.get_format(self.format_key)[0]))