From a9d5273f3ca91c8568959c79606332513608ec84 Mon Sep 17 00:00:00 2001 From: Akihiro Motoki Date: Wed, 26 Jan 2022 22:40:11 +0900 Subject: Address RemovedInDjango40Warning (1) force_text() is deprecated in favor of force_str() smart_text() is deprecated in favor of smart_str() https://docs.djangoproject.com/en/4.0/releases/3.0/#django-utils-encoding-force-text-and-smart-text Change-Id: Ic462fa8c3dfa26e8196df19fef5044036a9e97b4 --- horizon/exceptions.py | 10 +++++----- horizon/forms/fields.py | 21 ++++++++++----------- horizon/messages.py | 6 +++--- horizon/tables/base.py | 2 +- horizon/templatetags/horizon.py | 10 +++++----- horizon/test/helpers.py | 4 ++-- horizon/test/unit/test_base.py | 2 +- horizon/test/unit/test_exceptions.py | 8 ++++---- horizon/test/unit/test_messages.py | 6 +++--- horizon/utils/functions.py | 7 +++---- horizon/utils/lazy_encoder.py | 4 ++-- horizon/views.py | 4 ++-- horizon/workflows/base.py | 10 +++++----- .../project/instances/workflows/resize_instance.py | 2 +- .../dashboards/project/volumes/views.py | 2 +- .../dashboards/settings/user/forms.py | 2 +- openstack_dashboard/utils/config_types.py | 4 ++-- openstack_dashboard/views.py | 4 ++-- 18 files changed, 53 insertions(+), 55 deletions(-) diff --git a/horizon/exceptions.py b/horizon/exceptions.py index 240cdefaf..f6a88b22a 100644 --- a/horizon/exceptions.py +++ b/horizon/exceptions.py @@ -263,8 +263,8 @@ HANDLE_EXC_METHODS = [ def _append_detail(message, details): - return encoding.force_text(message) + SEPARATOR + \ - encoding.force_text(details) + return encoding.force_str(message) + SEPARATOR + \ + encoding.force_str(details) def handle(request, message=None, redirect=None, ignore=False, @@ -315,7 +315,7 @@ def handle(request, message=None, redirect=None, ignore=False, exc_type, exc_value, exc_traceback = exc_value.wrapped wrap = True - log_entry = encoding.force_text(exc_value) + log_entry = encoding.force_str(exc_value) user_message = "" # We trust messages from our own exceptions @@ -323,9 +323,9 @@ def handle(request, message=None, redirect=None, ignore=False, user_message = log_entry # If the message has a placeholder for the exception, fill it in elif message and "%(exc)s" in message: - user_message = encoding.force_text(message) % {"exc": log_entry} + user_message = encoding.force_str(message) % {"exc": log_entry} elif message: - user_message = encoding.force_text(message) + user_message = encoding.force_str(message) if details is None: user_message = _append_detail(user_message, exc_value) elif details: diff --git a/horizon/forms/fields.py b/horizon/forms/fields.py index f2db9fce3..68763f16d 100644 --- a/horizon/forms/fields.py +++ b/horizon/forms/fields.py @@ -27,7 +27,7 @@ from django.forms.utils import flatatt from django.forms import widgets from django.template.loader import get_template from django import urls -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils.functional import Promise from django.utils import html from django.utils.safestring import mark_safe @@ -242,7 +242,7 @@ class SelectWidget(widgets.Widget): return attrs def render_option(self, selected_choices, option_value, option_label): - option_value = force_text(option_value) + option_value = force_str(option_value) other_html = (' selected="selected"' if option_value in selected_choices else '') @@ -259,12 +259,12 @@ class SelectWidget(widgets.Widget): def render_options(self, selected_choices): # Normalize to strings. - selected_choices = set(force_text(v) for v in selected_choices) + selected_choices = set(force_str(v) for v in selected_choices) output = [] for option_value, option_label in self.choices: if isinstance(option_label, (list, tuple)): output.append(html.format_html( - '', force_text(option_value))) + '', force_str(option_value))) for option in option_label: output.append( self.render_option(selected_choices, *option)) @@ -279,8 +279,7 @@ class SelectWidget(widgets.Widget): if not isinstance(option_label, (str, Promise)): for data_attr in self.data_attrs: data_value = html.conditional_escape( - force_text(getattr(option_label, - data_attr, ""))) + force_str(getattr(option_label, data_attr, ""))) other_html.append('data-%s="%s"' % (data_attr, data_value)) return ' '.join(other_html) @@ -288,7 +287,7 @@ class SelectWidget(widgets.Widget): if (not isinstance(option_label, (str, Promise)) and callable(self.transform)): option_label = self.transform(option_label) - return html.conditional_escape(force_text(option_label)) + return html.conditional_escape(force_str(option_label)) def transform_option_html_attrs(self, option_label): if not callable(self.transform_html_attrs): @@ -473,8 +472,8 @@ class ChoiceInput(SubWidget): self.name = name self.value = value self.attrs = attrs - self.choice_value = force_text(choice[0]) - self.choice_label = force_text(choice[1]) + self.choice_value = force_str(choice[0]) + self.choice_label = force_str(choice[1]) self.index = index if 'id' in self.attrs: self.attrs['id'] += "_%d" % self.index @@ -529,7 +528,7 @@ class ThemableCheckboxChoiceInput(ChoiceInput): super().__init__(*args, **kwargs) # NOTE(e0ne): Django sets default value to None if self.value: - self.value = set(force_text(v) for v in self.value) + self.value = set(force_str(v) for v in self.value) def is_checked(self): if self.value: @@ -589,7 +588,7 @@ class ThemableCheckboxSelectMultiple(widgets.CheckboxSelectMultiple): self.name, self.value, self.attrs.copy(), choice, i) output.append(html.format_html( self.inner_html, - choice_value=force_text(w), + choice_value=force_str(w), sub_widgets='')) return html.format_html( self.outer_html, diff --git a/horizon/messages.py b/horizon/messages.py index f40adfa69..9e07b035e 100644 --- a/horizon/messages.py +++ b/horizon/messages.py @@ -19,12 +19,12 @@ messaging needs (e.g. AJAX communication, etc.). from django.contrib import messages as _messages from django.contrib.messages import constants -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils.safestring import SafeData def horizon_message_already_queued(request, message): - _message = force_text(message) + _message = force_str(message) if request.is_ajax(): for tag, msg, extra in request.horizon['async_messages']: if _message == msg: @@ -46,7 +46,7 @@ def add_message(request, level, message, extra_tags='', fail_silently=False): if isinstance(message, SafeData): extra_tags = extra_tags + ' safe' request.horizon['async_messages'].append([tag, - force_text(message), + force_str(message), extra_tags]) else: return _messages.add_message(request, level, message, diff --git a/horizon/tables/base.py b/horizon/tables/base.py index f3770f1bc..9bb0c866e 100644 --- a/horizon/tables/base.py +++ b/horizon/tables/base.py @@ -730,7 +730,7 @@ class Cell(html.HTMLElement): # those columns where truncate is False leads to multiple errors # in unit tests data = getattr(datum, column.name, '') or '' - data = encoding.force_text(data) + data = encoding.force_str(data) if len(data) > column.truncate: self.attrs['data-toggle'] = 'tooltip' self.attrs['title'] = data diff --git a/horizon/templatetags/horizon.py b/horizon/templatetags/horizon.py index 00912a2a2..48c95dd63 100644 --- a/horizon/templatetags/horizon.py +++ b/horizon/templatetags/horizon.py @@ -17,7 +17,7 @@ from collections import OrderedDict from django.conf import settings from django import template from django.template import Node -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils import translation from django.utils.translation import ugettext_lazy as _ @@ -34,7 +34,7 @@ class MinifiedNode(Node): def render(self, context): return ' '.join( - force_text(self.nodelist.render(context).strip()).split() + force_str(self.nodelist.render(context).strip()).split() ).replace(' > ', '>').replace(' <', '<') @@ -142,9 +142,9 @@ def quota(val, units=None): if val == float("inf"): return _("(No Limit)") if units is not None: - return "%s %s %s" % (val, force_text(units), - force_text(_("Available"))) - return "%s %s" % (val, force_text(_("Available"))) + return "%s %s %s" % (val, force_str(units), + force_str(_("Available"))) + return "%s %s" % (val, force_str(_("Available"))) @register.filter diff --git a/horizon/test/helpers.py b/horizon/test/helpers.py index 0d1723136..9da2d1aa7 100644 --- a/horizon/test/helpers.py +++ b/horizon/test/helpers.py @@ -38,7 +38,7 @@ from django import test as django_test from django.test.client import RequestFactory from django.test import tag from django.test import utils as django_test_utils -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.contrib.staticfiles.testing \ import StaticLiveServerTestCase as LiveServerTestCase @@ -230,7 +230,7 @@ class TestCase(django_test.TestCase): # Otherwise, make sure we got the expected messages. for msg_type, count in kwargs.items(): - msgs = [force_text(m.message) + msgs = [force_str(m.message) for m in messages if msg_type in m.tags] assert len(msgs) == count, \ "%s messages not as expected: %s" % (msg_type.title(), diff --git a/horizon/test/unit/test_base.py b/horizon/test/unit/test_base.py index 6e066f5c2..8a40d77fd 100644 --- a/horizon/test/unit/test_base.py +++ b/horizon/test/unit/test_base.py @@ -375,7 +375,7 @@ class GetUserHomeTests(test.TestCase): base.Horizon.get_user_home(self.test_user)) def test_using_module_function(self): - module_func = 'django.utils.encoding.force_text' + module_func = 'django.utils.encoding.force_str' settings.HORIZON_CONFIG['user_home'] = module_func conf.HORIZON_CONFIG._setup() diff --git a/horizon/test/unit/test_exceptions.py b/horizon/test/unit/test_exceptions.py index 796870876..e9d3bed49 100644 --- a/horizon/test/unit/test_exceptions.py +++ b/horizon/test/unit/test_exceptions.py @@ -10,7 +10,7 @@ # License for the specific language governing permissions and limitations # under the License. -from django.utils.encoding import force_text +from django.utils.encoding import force_str from horizon import exceptions from horizon.test import helpers as test @@ -25,9 +25,9 @@ class HandleTests(test.TestCase): # Japanese translation of: # 'Because the container is not empty, it can not be deleted.' - expected = ['error', force_text(translated_unicode + - exceptions.SEPARATOR + - translated_unicode), ''] + expected = ['error', force_str(translated_unicode + + exceptions.SEPARATOR + + translated_unicode), ''] req = self.request req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' diff --git a/horizon/test/unit/test_messages.py b/horizon/test/unit/test_messages.py index 92e95b53f..5cc516ebc 100644 --- a/horizon/test/unit/test_messages.py +++ b/horizon/test/unit/test_messages.py @@ -15,7 +15,7 @@ import json from django import http -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils.safestring import mark_safe from horizon import messages @@ -27,7 +27,7 @@ class MessageTests(test.TestCase): def test_middleware_header(self): req = self.request string = "Giant ants are attacking San Francisco!" - expected = ["error", force_text(string), ""] + expected = ["error", force_str(string), ""] self.assertIn("async_messages", req.horizon) self.assertCountEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' @@ -42,7 +42,7 @@ class MessageTests(test.TestCase): def test_error_message(self): req = self.request string = mark_safe("We are now safe from ants! Go here!") - expected = ["error", force_text(string), " safe"] + expected = ["error", force_str(string), " safe"] self.assertIn("async_messages", req.horizon) self.assertCountEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' diff --git a/horizon/utils/functions.py b/horizon/utils/functions.py index d454156af..b4d5622d5 100644 --- a/horizon/utils/functions.py +++ b/horizon/utils/functions.py @@ -20,14 +20,13 @@ from oslo_utils import units from django.conf import settings from django.contrib.auth import logout from django import http -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils.functional import lazy from django.utils import translation def _lazy_join(separator, strings): - return separator.join([force_text(s) - for s in strings]) + return separator.join([force_str(s) for s in strings]) lazy_join = lazy(_lazy_join, str) @@ -43,7 +42,7 @@ def add_logout_reason(request, response, reason, status='success'): # Store the translated string in the cookie lang = translation.get_language_from_request(request) with translation.override(lang): - reason = force_text(reason).encode('unicode_escape').decode('ascii') + reason = force_str(reason).encode('unicode_escape').decode('ascii') response.set_cookie('logout_reason', reason, max_age=10) response.set_cookie('logout_status', status, max_age=10) diff --git a/horizon/utils/lazy_encoder.py b/horizon/utils/lazy_encoder.py index e48d76a07..dd78539c0 100644 --- a/horizon/utils/lazy_encoder.py +++ b/horizon/utils/lazy_encoder.py @@ -13,7 +13,7 @@ # under the License. from django.core.serializers.json import DjangoJSONEncoder -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils.functional import Promise @@ -21,5 +21,5 @@ class LazyTranslationEncoder(DjangoJSONEncoder): """JSON encoder that resolves lazy objects like translations""" def default(self, obj): if isinstance(obj, Promise): - return force_text(obj) + return force_str(obj) return super().default(obj) diff --git a/horizon/views.py b/horizon/views.py index 532c43520..413c6187c 100644 --- a/horizon/views.py +++ b/horizon/views.py @@ -53,9 +53,9 @@ class PageTitleMixin(object): if "page_title" not in context: con = template.Context(context) - # NOTE(sambetts): Use force_text to ensure lazy translations + # NOTE(sambetts): Use force_str to ensure lazy translations # are handled correctly. - temp = template.Template(encoding.force_text(self.page_title)) + temp = template.Template(encoding.force_str(self.page_title)) context["page_title"] = temp.render(con) return context diff --git a/horizon/workflows/base.py b/horizon/workflows/base.py index 4ceafaf9a..66bdb2df5 100644 --- a/horizon/workflows/base.py +++ b/horizon/workflows/base.py @@ -26,7 +26,7 @@ from django.template.defaultfilters import linebreaks from django.template.defaultfilters import safe from django.template.defaultfilters import slugify from django import urls -from django.utils.encoding import force_text +from django.utils.encoding import force_str from django.utils import module_loading from django.utils.translation import ugettext_lazy as _ from openstack_auth import policy @@ -163,7 +163,7 @@ class Action(forms.Form, metaclass=ActionMetaclass): self.required_css_class = 'required' def __str__(self): - return force_text(self.name) + return force_str(self.name) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.slug) @@ -182,7 +182,7 @@ class Action(forms.Form, metaclass=ActionMetaclass): tmpl = template.loader.get_template(self.help_text_template) text += tmpl.render(extra_context, self.request) else: - text += linebreaks(force_text(self.help_text)) + text += linebreaks(force_str(self.help_text)) return safe(text) def add_action_error(self, message): @@ -310,7 +310,7 @@ class Step(object): return "<%s: %s>" % (self.__class__.__name__, self.slug) def __str__(self): - return force_text(self.name) + return force_str(self.name) def __init__(self, workflow): super().__init__() @@ -453,7 +453,7 @@ class Step(object): def get_help_text(self): """Returns the help text for this step.""" - text = linebreaks(force_text(self.help_text)) + text = linebreaks(force_str(self.help_text)) text += self.action.get_help_text() return safe(text) diff --git a/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py b/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py index 00d25938f..d5151002f 100644 --- a/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py +++ b/openstack_dashboard/dashboards/project/instances/workflows/resize_instance.py @@ -155,5 +155,5 @@ class ResizeInstance(workflows.Workflow): api.nova.server_resize(request, instance_id, flavor, disk_config) return True except Exception as e: - self.failure_message = encoding.force_text(e) + self.failure_message = encoding.force_str(e) return False diff --git a/openstack_dashboard/dashboards/project/volumes/views.py b/openstack_dashboard/dashboards/project/volumes/views.py index 0b52af896..3fe3ff2ca 100644 --- a/openstack_dashboard/dashboards/project/volumes/views.py +++ b/openstack_dashboard/dashboards/project/volumes/views.py @@ -278,7 +278,7 @@ class CreateView(forms.ModalFormView): _("If \"No volume type\" is selected, the volume will be " "created without a volume type.") - no_type_description = encoding.force_text(message) + no_type_description = encoding.force_str(message) type_descriptions = [{'name': '', 'description': no_type_description}] + \ diff --git a/openstack_dashboard/dashboards/settings/user/forms.py b/openstack_dashboard/dashboards/settings/user/forms.py index b573d6b97..e1deb940a 100644 --- a/openstack_dashboard/dashboards/settings/user/forms.py +++ b/openstack_dashboard/dashboards/settings/user/forms.py @@ -120,6 +120,6 @@ class UserSettingsForm(forms.SelfHandlingForm): with translation.override(lang_code): messages.success(request, - encoding.force_text(_("Settings saved."))) + encoding.force_str(_("Settings saved."))) return response diff --git a/openstack_dashboard/utils/config_types.py b/openstack_dashboard/utils/config_types.py index 5eae5760a..74a2d20cd 100644 --- a/openstack_dashboard/utils/config_types.py +++ b/openstack_dashboard/utils/config_types.py @@ -93,7 +93,7 @@ class Translate(types.ConfigType): def _formatter(self, value): return self.quote_trailing_and_leading_space( - encoding.force_text(value)) + encoding.force_str(value)) class Literal(types.ConfigType): @@ -181,7 +181,7 @@ class Literal(types.ConfigType): return '(%s)' % ', '.join(self._format(value) for value in result) if isinstance(result, functional.Promise): # Lazy translatable string. - return repr(encoding.force_text(result)) + return repr(encoding.force_str(result)) return repr(result) def _formatter(self, value): diff --git a/openstack_dashboard/views.py b/openstack_dashboard/views.py index 511ebd929..1c03c85db 100644 --- a/openstack_dashboard/views.py +++ b/openstack_dashboard/views.py @@ -20,7 +20,7 @@ from django.conf import settings from django import http from django import shortcuts from django import urls -from django.utils.encoding import smart_text +from django.utils.encoding import smart_str import django.views.decorators.vary from django.views.generic import TemplateView @@ -96,7 +96,7 @@ class ExtensibleHeaderView(TemplateView): response = view.get(self.request) rendered_response = response.render() packed_response = [view_path.replace('.', '-'), - smart_text(rendered_response.content)] + smart_str(rendered_response.content)] header_sections.append(packed_response) except Exception as e: -- cgit v1.2.1