1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Refs #27795 -- Replaced many force_text() with str()

Thanks Tim Graham for the review.
This commit is contained in:
Claude Paroz
2017-04-21 19:52:26 +02:00
parent 8ab7ce8558
commit 301de774c2
47 changed files with 135 additions and 181 deletions

View File

@@ -4,7 +4,6 @@ import warnings
from django.forms.utils import flatatt, pretty_name
from django.forms.widgets import Textarea, TextInput
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.html import conditional_escape, format_html, html_safe
from django.utils.inspect import func_supports_parameter
@@ -213,9 +212,9 @@ class BoundField:
Calculate and return the ID attribute for this BoundField, if the
associated Form has specified auto_id. Return an empty string otherwise.
"""
auto_id = self.form.auto_id
if auto_id and '%s' in force_text(auto_id):
return force_text(auto_id) % self.html_name
auto_id = self.form.auto_id # Boolean or string
if auto_id and '%s' in str(auto_id):
return auto_id % self.html_name
elif auto_id:
return self.html_name
return ''

View File

@@ -28,7 +28,6 @@ from django.forms.widgets import (
from django.utils import formats
from django.utils.dateparse import parse_duration
from django.utils.duration import duration_string
from django.utils.encoding import force_text
from django.utils.ipv6 import clean_ipv6_address
from django.utils.translation import gettext_lazy as _, ngettext_lazy
@@ -221,7 +220,7 @@ class CharField(Field):
"""Return a string."""
if value in self.empty_values:
return self.empty_value
value = force_text(value)
value = str(value)
if self.strip:
value = value.strip()
return value
@@ -268,7 +267,7 @@ class IntegerField(Field):
value = formats.sanitize_separators(value)
# Strip trailing decimal and zeros.
try:
value = int(self.re_decimal.sub('', force_text(value)))
value = int(self.re_decimal.sub('', str(value)))
except (ValueError, TypeError):
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
@@ -341,7 +340,7 @@ class DecimalField(IntegerField):
return None
if self.localize:
value = formats.sanitize_separators(value)
value = force_text(value).strip()
value = str(value).strip()
try:
value = Decimal(value)
except DecimalException:
@@ -484,7 +483,7 @@ class DurationField(Field):
return None
if isinstance(value, datetime.timedelta):
return value
value = parse_duration(force_text(value))
value = parse_duration(str(value))
if value is None:
raise ValidationError(self.error_messages['invalid'], code='invalid')
return value
@@ -784,7 +783,7 @@ class ChoiceField(Field):
"""Return a string."""
if value in self.empty_values:
return ''
return force_text(value)
return str(value)
def validate(self, value):
"""Validate that the input is in self.choices."""
@@ -798,15 +797,15 @@ class ChoiceField(Field):
def valid_value(self, value):
"""Check to see if the provided value is a valid choice."""
text_value = force_text(value)
text_value = str(value)
for k, v in self.choices:
if isinstance(v, (list, tuple)):
# This is an optgroup, so look inside the group for options
for k2, v2 in v:
if value == k2 or text_value == force_text(k2):
if value == k2 or text_value == str(k2):
return True
else:
if value == k or text_value == force_text(k):
if value == k or text_value == str(k):
return True
return False
@@ -851,7 +850,7 @@ class MultipleChoiceField(ChoiceField):
return []
elif not isinstance(value, (list, tuple)):
raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')
return [force_text(val) for val in value]
return [str(val) for val in value]
def validate(self, value):
"""Validate that the input is a list or tuple."""
@@ -873,8 +872,8 @@ class MultipleChoiceField(ChoiceField):
data = []
if len(initial) != len(data):
return True
initial_set = set(force_text(value) for value in initial)
data_set = set(force_text(value) for value in data)
initial_set = set(str(value) for value in initial)
data_set = set(str(value) for value in data)
return data_set != initial_set

View File

@@ -12,7 +12,6 @@ from django.forms.fields import Field, FileField
# pretty_name is imported for backwards compatibility in Django 1.9
from django.forms.utils import ErrorDict, ErrorList, pretty_name # NOQA
from django.forms.widgets import Media, MediaDefiningClass
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.html import conditional_escape, html_safe
from django.utils.safestring import mark_safe
@@ -205,7 +204,7 @@ class BaseForm:
if bf.is_hidden:
if bf_errors:
top_errors.extend(
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': force_text(e)}
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': str(e)}
for e in bf_errors])
hidden_fields.append(str(bf))
else:
@@ -216,10 +215,10 @@ class BaseForm:
html_class_attr = ' class="%s"' % css_classes
if errors_on_separate_row and bf_errors:
output.append(error_row % force_text(bf_errors))
output.append(error_row % str(bf_errors))
if bf.label:
label = conditional_escape(force_text(bf.label))
label = conditional_escape(bf.label)
label = bf.label_tag(label) or ''
else:
label = ''

View File

@@ -16,7 +16,6 @@ from django.forms.utils import ErrorList
from django.forms.widgets import (
HiddenInput, MultipleHiddenInput, SelectMultiple,
)
from django.utils.encoding import force_text
from django.utils.text import capfirst, get_text_list
from django.utils.translation import gettext, gettext_lazy as _
@@ -1085,7 +1084,7 @@ class InlineForeignKeyField(Field):
orig = getattr(self.parent_instance, self.to_field)
else:
orig = self.parent_instance.pk
if force_text(value) != force_text(orig):
if str(value) != str(orig):
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
return self.parent_instance
@@ -1176,7 +1175,7 @@ class ModelChoiceField(ChoiceField):
presented by this object. Subclasses can override this method to
customize the display of the choices.
"""
return force_text(obj)
return str(obj)
def _get_choices(self):
# If self._choices is set, then somebody must have manually set
@@ -1219,7 +1218,7 @@ class ModelChoiceField(ChoiceField):
def has_changed(self, initial, data):
initial_value = initial if initial is not None else ''
data_value = data if data is not None else ''
return force_text(self.prepare_value(initial_value)) != force_text(data_value)
return str(self.prepare_value(initial_value)) != str(data_value)
class ModelMultipleChoiceField(ModelChoiceField):
@@ -1286,9 +1285,9 @@ class ModelMultipleChoiceField(ModelChoiceField):
params={'pk': pk},
)
qs = self.queryset.filter(**{'%s__in' % key: value})
pks = set(force_text(getattr(o, key)) for o in qs)
pks = set(str(getattr(o, key)) for o in qs)
for val in value:
if force_text(val) not in pks:
if str(val) not in pks:
raise ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
@@ -1310,8 +1309,8 @@ class ModelMultipleChoiceField(ModelChoiceField):
data = []
if len(initial) != len(data):
return True
initial_set = set(force_text(value) for value in self.prepare_value(initial))
data_set = set(force_text(value) for value in data)
initial_set = set(str(value) for value in self.prepare_value(initial))
data_set = set(str(value) for value in data)
return data_set != initial_set

View File

@@ -12,7 +12,6 @@ from django.forms.utils import to_current_timezone
from django.templatetags.static import static
from django.utils import datetime_safe, formats
from django.utils.dates import MONTHS
from django.utils.encoding import force_text
from django.utils.formats import get_format
from django.utils.html import format_html, html_safe
from django.utils.safestring import mark_safe
@@ -184,7 +183,7 @@ class Widget(metaclass=MediaDefiningClass):
return None
if self.is_localized:
return formats.localize_input(value)
return force_text(value)
return str(value)
def get_context(self, name, value, attrs):
context = {}
@@ -483,7 +482,7 @@ class CheckboxInput(Input):
"""Only return the 'value' attribute if value isn't empty."""
if value is True or value is False or value is None or value == '':
return
return force_text(value)
return str(value)
def get_context(self, name, value, attrs):
if self.check_test(value):
@@ -570,7 +569,7 @@ class ChoiceWidget(Widget):
for subvalue, sublabel in choices:
selected = (
force_text(subvalue) in value and
str(subvalue) in value and
(not has_selected or self.allow_multiple_selected)
)
if selected and not has_selected: