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: messages.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 #2
Source File: formats.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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: renderers.py    From django-rest-framework-xml with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #4
Source File: logutil.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #6
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #7
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #8
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #9
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 #11
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #12
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #13
Source File: tests.py    From django-admin-rangefilter with MIT License 6 votes vote down vote up
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 #14
Source File: renderers.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #15
Source File: errorpages.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def process_exception(self, request, exception):
        msg = force_str(exception)
        if isinstance(exception, Http404):
            if request.is_ajax():
                return JsonResponseNotFound({"msg": msg})
        elif isinstance(exception, Http400):
            if request.is_ajax():
                return JsonResponseBadRequest({"msg": msg})
        elif isinstance(exception, PermissionDenied):
            if request.is_ajax():
                return JsonResponseForbidden({"msg": msg})

            ctx = {
                "permission_error": msg,
            }

            if not request.user.is_authenticated:
                msg_args = {
                    "login_link": reverse("account_login"),
                }
                login_msg = _(
                    'You need to <a class="js-login" '
                    'href="%(login_link)s">login</a> to access this page.' % msg_args
                )
                ctx["login_message"] = login_msg

            return HttpResponseForbidden(
                render_to_string("errors/403.html", context=ctx, request=request)
            )
        elif exception.__class__.__name__ in (
            "OperationalError",
            "ProgrammingError",
            "DatabaseError",
        ):
            # HACKISH: Since exceptions thrown by different databases do not
            # share the same class heirarchy (DBAPI2 sucks) we have to check
            # the class name instead. Since python uses duck typing I will call
            # this poking-the-duck-until-it-quacks-like-a-duck-test
            return handle_exception(request, exception, "errors/db.html")
        else:
            return handle_exception(request, exception, "errors/500.html") 
Example #16
Source File: json.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def default(self, obj):
        if (
            isinstance(obj, datetime.datetime)
            or isinstance(obj, datetime.date)
            or isinstance(obj, datetime.time)
        ):
            return int(dateformat.format(obj, "U"))

        try:
            return super().default(obj)
        except TypeError:
            return force_str(obj) 
Example #17
Source File: reports.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_preprocess_function(self, field, value, export_format):
        """ Returns the preprocessing function for a given field name, field value, and export format"""

        # Try to find a field specific function and return it
        format_dict = self.custom_field_preprocess.get(field, {})
        if export_format in format_dict:
            return format_dict[export_format]

        # Otherwise check for a value class specific function
        for value_classes, format_dict in self.custom_value_preprocess.items():
            if isinstance(value, value_classes) and export_format in format_dict:
                return format_dict[export_format]

        # Finally resort to force_str to prevent encoding errors
        return force_str 
Example #18
Source File: test_model_viewsets.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_key_in_list_result(self):
        """
        Ensure the result has a 'user' key since that is the name of the model
        """
        with override_settings(JSON_API_FORMAT_FIELD_NAMES='dasherize'):
            response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, 200)

        user = get_user_model().objects.all()[0]
        expected = {
            'data': [
                {
                    'type': 'users',
                    'id': encoding.force_str(user.pk),
                    'attributes': {
                        'first-name': user.first_name,
                        'last-name': user.last_name,
                        'email': user.email
                    },
                }
            ],
            'links': {
                'first': 'http://testserver/identities?page%5Bnumber%5D=1',
                'last': 'http://testserver/identities?page%5Bnumber%5D=2',
                'next': 'http://testserver/identities?page%5Bnumber%5D=2',
                'prev': None
            },
            'meta': {
                'pagination': {
                    'page': 1,
                    'pages': 2,
                    'count': 2
                }
            }
        }

        assert expected == response.json() 
Example #19
Source File: test_sideload_resources.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_get_sideloaded_data(self):
        """
        Ensure resources that are meant for sideloaded data
        do not return a single root key.
        """
        response = self.client.get(self.url)
        content = json.loads(response.content.decode('utf8'))

        self.assertEqual(
            sorted(content.keys()),
            [encoding.force_str('identities'),
             encoding.force_str('posts')]) 
Example #20
Source File: identity.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def posts(self, request):
        self.resource_name = False

        identities = self.queryset
        posts = [{'id': 1, 'title': 'Test Blog Post'}]

        data = {
            encoding.force_str('identities'): IdentitySerializer(identities, many=True).data,
            encoding.force_str('posts'): PostSerializer(posts, many=True).data,
        }
        return Response(utils.format_field_names(data, format_type='camelize')) 
Example #21
Source File: fields.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def generate_filename(self, instance, filename):
        path_parts = []

        if self.upload_to:
            # Support the upload_to callable that Django provides
            if callable(self.upload_to):
                dirname, filename = os.path.split(self.upload_to(instance, filename))
                path_parts.append(dirname)
            else:
                dirname = force_text(datetime.datetime.now().strftime(force_str(self.upload_to)))
                path_parts.append(dirname)

        # Add our custom subdir function.
        upload_subfolder = self.upload_subfolder
        if upload_subfolder:
            # Should return a list, so joining can be done in a storage-specific manner.
            extra_dirs = upload_subfolder(instance)

            # Avoid mistakes by developers, no "s/u/b/p/a/t/h/"
            if isinstance(extra_dirs, string_types):
                warnings.warn("{}.{}.upload_subfolder should return a list"
                              " to avoid path-separator issues.".format(
                    instance.__class__.__name__, self.name), UserWarning)
                extra_dirs = os.path.split(extra_dirs)

            path_parts.extend([self.storage.get_valid_name(dir) for dir in extra_dirs])

        path_parts.append(self._get_clean_filename(filename))
        if django.VERSION >= (1, 10):
            filename = posixpath.join(*path_parts)
            return self.storage.generate_filename(filename)
        else:
            return os.path.join(*path_parts) 
Example #22
Source File: filters.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def strptime(self, value, format):
        return parse_datetime(force_str(value)) 
Example #23
Source File: acl.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    this is analog to django's builtin ``permission_required`` decorator, but
    improved to check per slug ACLRules and default permissions for
    anonymous and logged in users

    if there is a rule affecting a slug, the user needs to be part of the
    rule's allowed users. If there isn't a matching rule, defaults permissions
    apply.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
                return view_func(request, *args, **kwargs)
            if is_authenticated(request.user):
                if WALIKI_RENDER_403:
                    return render(request, 'waliki/403.html', kwargs, status=403)
                else:
                    raise PermissionDenied

            path = request.build_absolute_uri()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                resolve_url(login_url or settings.LOGIN_URL))
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view

    return decorator 
Example #24
Source File: forms.py    From django-sundial with MIT License 5 votes vote down vote up
def run_validators(self, value):
        return super().run_validators(force_str(value)) 
Example #25
Source File: utils.py    From django-sundial with MIT License 5 votes vote down vote up
def set_session_timezone(session, zone):
    session[TIMEZONE_SESSION_KEY] = force_str(zone) 
Example #26
Source File: fields.py    From django-sundial with MIT License 5 votes vote down vote up
def get_prep_value(self, value):
        if value is not None:
            value = force_str(value)
        return value 
Example #27
Source File: fields.py    From django-sundial with MIT License 5 votes vote down vote up
def run_validators(self, value):
        super().run_validators(force_str(value)) 
Example #28
Source File: fields.py    From django-sundial with MIT License 5 votes vote down vote up
def validate(self, value, model_instance):
        super().validate(force_str(value), model_instance) 
Example #29
Source File: filter.py    From django-admin-rangefilter with MIT License 5 votes vote down vote up
def choices(self, cl):
        yield {
            # slugify converts any non-unicode characters to empty characters
            # but system_name is required, if title converts to empty string use id
            # https://github.com/silentsokolov/django-admin-rangefilter/issues/18
            'system_name': force_str(slugify(self.title) if slugify(self.title) else id(self.title)),
            'query_string': cl.get_query_string(
                {}, remove=self._get_expected_fields()
            )
        } 
Example #30
Source File: test_hashid.py    From django-hashid-field with MIT License 5 votes vote down vote up
def test_force_text(self):
        h = Hashid(2923)
        t = force_str(h)
        self.assertEqual(t, h.hashid)