Python django.utils.encoding.force_str() Examples
The following are 30
code examples of django.utils.encoding.force_str().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.encoding
, or try the search function
.

Example #1
Source File: logutil.py From donation-tracker with Apache License 2.0 | 6 votes |
def change(request, object, message_or_fields): """ Log that an object has been successfully changed. The argument *message_or_fields* must be a sequence of modified field names or a custom change message. """ if isinstance(message_or_fields, str): message = message_or_fields else: message = get_change_message(message_or_fields) models.LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(object).pk, object_id=object.pk, object_repr=force_str(object), action_flag=models.CHANGE, change_message=message, )
Example #2
Source File: formats.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def localize_input(value, default=None): """ Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0]) return value.strftime(format) return value
Example #3
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_connection_params(self): settings_dict = self.settings_dict # None may be used to connect to the default 'postgres' db if settings_dict['NAME'] == '': from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value.") conn_params = { 'database': settings_dict['NAME'] or 'postgres', } conn_params.update(settings_dict['OPTIONS']) conn_params.pop('isolation_level', None) if settings_dict['USER']: conn_params['user'] = settings_dict['USER'] if settings_dict['PASSWORD']: conn_params['password'] = force_str(settings_dict['PASSWORD']) if settings_dict['HOST']: conn_params['host'] = settings_dict['HOST'] if settings_dict['PORT']: conn_params['port'] = settings_dict['PORT'] return conn_params
Example #4
Source File: base.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_connection_params(self): kwargs = { 'conv': django_conversions, 'charset': 'utf8', } if six.PY2: kwargs['use_unicode'] = True settings_dict = self.settings_dict if settings_dict['USER']: kwargs['user'] = settings_dict['USER'] if settings_dict['NAME']: kwargs['db'] = settings_dict['NAME'] if settings_dict['PASSWORD']: kwargs['passwd'] = force_str(settings_dict['PASSWORD']) if settings_dict['HOST'].startswith('/'): kwargs['unix_socket'] = settings_dict['HOST'] elif settings_dict['HOST']: kwargs['host'] = settings_dict['HOST'] if settings_dict['PORT']: kwargs['port'] = int(settings_dict['PORT']) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs['client_flag'] = CLIENT.FOUND_ROWS kwargs.update(settings_dict['OPTIONS']) return kwargs
Example #5
Source File: messages.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def __str__(self): from django.db import models if self.obj is None: obj = "?" elif isinstance(self.obj, models.base.ModelBase): # We need to hardcode ModelBase and Field cases because its __str__ # method doesn't return "applabel.modellabel" and cannot be changed. model = self.obj app = model._meta.app_label obj = '%s.%s' % (app, model._meta.object_name) else: obj = force_str(self.obj) id = "(%s) " % self.id if self.id else "" hint = "\n\tHINT: %s" % self.hint if self.hint else '' return "%s: %s%s%s" % (obj, id, self.msg, hint)
Example #6
Source File: renderers.py From django-rest-framework-json-api with BSD 2-Clause "Simplified" License | 6 votes |
def build_json_resource_obj(cls, fields, resource, resource_instance, resource_name, force_type_resolution=False): """ Builds the resource object (type, id, attributes) and extracts relationships. """ # Determine type from the instance if the underlying model is polymorphic if force_type_resolution: resource_name = utils.get_resource_type_from_instance(resource_instance) resource_data = [ ('type', resource_name), ('id', encoding.force_str(resource_instance.pk) if resource_instance else None), ('attributes', cls.extract_attributes(fields, resource)), ] relationships = cls.extract_relationships(fields, resource, resource_instance) if relationships: resource_data.append(('relationships', relationships)) # Add 'self' link if field is present and valid if api_settings.URL_FIELD_NAME in resource and \ isinstance(fields[api_settings.URL_FIELD_NAME], relations.RelatedField): resource_data.append(('links', {'self': resource[api_settings.URL_FIELD_NAME]})) return OrderedDict(resource_data)
Example #7
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datefilter_filtered(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTAdmin(RangeModelDT, site) request = self.request_factory.get('/', {'created_at__range__gte': self.today, 'created_at__range__lte': self.tomorrow}) request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
Example #8
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datefilter_with_default(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTAdmin(RangeModelDT, site) modeladmin.get_rangefilter_created_at_default = lambda r: [self.today, self.tomorrow] request = self.request_factory.get('/') request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') self.assertEqual(filterspec.default_gte, self.today) self.assertEqual(filterspec.default_lte, self.tomorrow)
Example #9
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datefilter_filtered_with_one_params(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTAdmin(RangeModelDT, site) request = self.request_factory.get('/', {'created_at__range__gte': self.today}) request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
Example #10
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datefilter_filtered_datefield(self): self.request_factory = RequestFactory() modeladmin = RangeModelDAdmin(RangeModelD, site) request = self.request_factory.get('/', {'created_at__range__gte': self.today, 'created_at__range__lte': self.tomorrow}) request.user = self.user changelist = self.get_changelist(request, RangeModelD, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book_date]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
Example #11
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datetimfilter_filtered(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site) request = self.request_factory.get('/', {'created_at__range__gte_0': self.today, 'created_at__range__gte_1': self.min_time, 'created_at__range__lte_0': self.tomorrow, 'created_at__range__lte_1': self.max_time}) request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
Example #12
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datetimfilter_with_default(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site) modeladmin.get_rangefilter_created_at_default = lambda r: [self.today, self.tomorrow] request = self.request_factory.get('/') request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.djangonaut_book, self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') self.assertEqual(filterspec.default_gte, self.today) self.assertEqual(filterspec.default_lte, self.tomorrow)
Example #13
Source File: tests.py From django-admin-rangefilter with MIT License | 6 votes |
def test_datefilter_filtered_with_one_params(self): self.request_factory = RequestFactory() modeladmin = RangeModelDTTimeAdmin(RangeModelDT, site) request = self.request_factory.get('/', {'created_at__range__gte_0': self.today, 'created_at__range__gte_1': self.min_time}) request.user = self.user changelist = self.get_changelist(request, RangeModelDT, modeladmin) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_str(filterspec.title), 'created at') choice = select_by(filterspec.choices(changelist)) self.assertEqual(choice['query_string'], '?') self.assertEqual(choice['system_name'], 'created-at')
Example #14
Source File: renderers.py From django-rest-framework-xml with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement(self.item_tag_name, {}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) elif isinstance(data, dict): for key, value in data.items(): xml.startElement(key, {}) self._to_xml(xml, value) xml.endElement(key) elif data is None: # Don't output any value pass else: xml.characters(force_str(data))
Example #15
Source File: logutil.py From donation-tracker with Apache License 2.0 | 5 votes |
def addition(request, object): """ Log that an object has been successfully added. """ models.LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(object).pk, object_id=object.pk, object_repr=force_str(object), action_flag=models.ADDITION, )
Example #16
Source File: logutil.py From donation-tracker with Apache License 2.0 | 5 votes |
def deletion(request, object, object_repr=None): """ Log that an object will be deleted. """ models.LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(object).pk, object_id=object.pk, object_repr=object_repr or force_str(object), action_flag=models.DELETION, )
Example #17
Source File: dates.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'): """ Helper: get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date. """ format = delim.join((year_format, month_format, day_format)) datestr = delim.join((year, month, day)) try: return datetime.datetime.strptime(force_str(datestr), format).date() except ValueError: raise Http404(_("Invalid date string '%(datestr)s' given format '%(format)s'") % { 'datestr': datestr, 'format': format, })
Example #18
Source File: fields.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def strptime(self, value, format): return datetime.datetime.strptime(force_str(value), format).date()
Example #19
Source File: fields.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def strptime(self, value, format): return datetime.datetime.strptime(force_str(value), format).time()
Example #20
Source File: fields.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def strptime(self, value, format): return datetime.datetime.strptime(force_str(value), format)
Example #21
Source File: widgets.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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 else: match = RE_DATE.match(value) if match: year_val, month_val, day_val = [int(v) for v 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(six.iteritems(self.months)) 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 _parse_date_fmt(): output.append(html[field]) return mark_safe('\n'.join(output))
Example #22
Source File: formats.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language() cache_key = (format_type, lang) try: cached = _format_cache[cache_key] if cached is not None: return cached else: # Return the general setting by default return getattr(settings, format_type) except KeyError: for module in get_format_modules(lang): try: val = getattr(module, format_type) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: if isinstance(val, tuple): val = list(val) val.append(iso_input) _format_cache[cache_key] = val return val except AttributeError: pass _format_cache[cache_key] = None return getattr(settings, format_type)
Example #23
Source File: http.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def urlquote(url, safe='/'): """ A version of Python's urllib.quote() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote(force_str(url), force_str(safe)))
Example #24
Source File: http.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def urlquote_plus(url, safe=''): """ A version of Python's urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent iri_to_uri() call without double-quoting occurring. """ return force_text(quote_plus(force_str(url), force_str(safe)))
Example #25
Source File: http.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def urlunquote(quoted_url): """ A wrapper for Python's urllib.unquote() function that can operate on the result of django.utils.http.urlquote(). """ return force_text(unquote(force_str(quoted_url)))
Example #26
Source File: http.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def urlencode(query, doseq=0): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, 'items'): query = query.items() return original_urlencode( [(force_str(k), [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v)) for k, v in query], doseq)
Example #27
Source File: cookie.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def load(self, rawdata): self.bad_cookies = set() if six.PY2 and isinstance(rawdata, six.text_type): rawdata = force_str(rawdata) super(SimpleCookie, self).load(rawdata) for key in self.bad_cookies: del self[key] # override private __set() method: # (needed for using our Morsel, and for laxness with CookieError
Example #28
Source File: cookie.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def _BaseCookie__set(self, key, real_value, coded_value): key = force_str(key) try: M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M) except http_cookies.CookieError: if not hasattr(self, 'bad_cookies'): self.bad_cookies = set() self.bad_cookies.add(key) dict.__setitem__(self, key, http_cookies.Morsel())
Example #29
Source File: files.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_directory_name(self): return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
Example #30
Source File: utils.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
def get_runner(settings, test_runner_class=None): if not test_runner_class: test_runner_class = settings.TEST_RUNNER test_path = test_runner_class.split('.') # Allow for Python 2.5 relative paths if len(test_path) > 1: test_module_name = '.'.join(test_path[:-1]) else: test_module_name = '.' test_module = __import__(test_module_name, {}, {}, force_str(test_path[-1])) test_runner = getattr(test_module, test_path[-1]) return test_runner