Python django.utils.encoding.force_text() Examples

The following are 30 code examples of django.utils.encoding.force_text(). 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: widgets.py    From django-fontawesome with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def render_option(self, selected_choices, option_value, option_label):
            if option_value is None:
                option_value = ''
            option_value = force_text(option_value)
            if option_value in selected_choices:
                selected_html = mark_safe(' selected="selected"')
                if not self.allow_multiple_selected:
                    # Only allow for a single selection.
                    selected_choices.remove(option_value)
            else:
                selected_html = ''
            return format_html('<option data-icon="{0}" value="{0}"{1}>{2}</option>',
                option_value,
                selected_html,
                force_text(option_label),
            ) 
Example #2
Source File: rest.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def _get_cache_key(self, request):
        """
        Generate cache key that's exactly unique enough.

        Assumes that the response is determined by the request.method, authenticated user, and URL path.
        """
        # HTTP method
        method = request.method

        # Authenticated username
        if not request.user.is_authenticated or self.cache_ignore_auth:
            username = '*'
        else:
            username = request.user.username

        # URL path
        url = force_text(iri_to_uri(request.get_full_path()))

        # build a cache key out of that
        key = '#'.join(('CacheMixin', self.key_prefix, username, method, url))
        if len(key) > MAX_KEY_LENGTH:
            # make sure keys don't get too long
            key = key[:(MAX_KEY_LENGTH - 33)] + '-' + hashlib.md5(key.encode('utf8')).hexdigest()

        return key 
Example #3
Source File: dashboard.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        if DJANGO_11:
            final_attrs = self.build_attrs(attrs, extra_attrs={'name': name})
        else:
            final_attrs = self.build_attrs(attrs, name=name)
        final_attrs['class'] = 'nav nav-pills nav-stacked'
        output = [u'<ul%s>' % flatatt(final_attrs)]
        options = self.render_options(force_text(value), final_attrs['id'])
        if options:
            output.append(options)
        output.append(u'</ul>')
        output.append('<input type="hidden" id="%s_input" name="%s" value="%s"/>' %
                      (final_attrs['id'], name, force_text(value)))
        return mark_safe(u'\n'.join(output)) 
Example #4
Source File: list.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        """
        Prepare the context for templates.
        """
        self.title = _('%s List') % force_text(self.opts.verbose_name)
        model_fields = [(f, f.name in self.list_display, self.get_check_field_url(f))
                        for f in (list(self.opts.fields) + self.get_model_method_fields()) if f.name not in self.list_exclude]

        new_context = {
            'model_name': force_text(self.opts.verbose_name_plural),
            'title': self.title,
            'cl': self,
            'model_fields': model_fields,
            'clean_select_field_url': self.get_query_string(remove=[COL_LIST_VAR]),
            'has_add_permission': self.has_add_permission(),
            'app_label': self.app_label,
            'brand_name': self.opts.verbose_name_plural,
            'brand_icon': self.get_model_icon(self.model),
            'add_url': self.model_admin_url('add'),
            'result_headers': self.result_headers(),
            'results': self.results()
        }
        context = super(ListAdminView, self).get_context()
        context.update(new_context)
        return context 
Example #5
Source File: delete.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def init_request(self, object_id, *args, **kwargs):
        "The 'delete' admin view for this model."
        self.obj = self.get_object(unquote(object_id))

        if not self.has_delete_permission(self.obj):
            raise PermissionDenied

        if self.obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})

        using = router.db_for_write(self.model)

        # Populate deleted_objects, a data structure of all related objects that
        # will also be deleted.
        (self.deleted_objects, model_count, self.perms_needed, self.protected) = get_deleted_objects(
            [self.obj], self.opts, self.request.user, self.admin_site, using) 
Example #6
Source File: delete.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        if self.perms_needed or self.protected:
            title = _("Cannot delete %(name)s") % {"name":
                                                   force_text(self.opts.verbose_name)}
        else:
            title = _("Are you sure?")

        new_context = {
            "title": title,
            "object": self.obj,
            "deleted_objects": self.deleted_objects,
            "perms_lacking": self.perms_needed,
            "protected": self.protected,
        }
        context = super(DeleteAdminView, self).get_context()
        context.update(new_context)
        return context 
Example #7
Source File: detail.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        new_context = {
            'title': _('%s Detail') % force_text(self.opts.verbose_name),
            'form': self.form_obj,

            'object': self.obj,

            'has_change_permission': self.has_change_permission(self.obj),
            'has_delete_permission': self.has_delete_permission(self.obj),

            'content_type_id': ContentType.objects.get_for_model(self.model).id,
        }

        context = super(DetailAdminView, self).get_context()
        context.update(new_context)
        return context 
Example #8
Source File: tests.py    From longclaw with MIT License 6 votes vote down vote up
def test_create_order_with_basket_shipping_option(self):
        amount = 11
        rate = ShippingRate.objects.create(
            name=force_text(uuid.uuid4()),
            rate=amount,
            carrier=force_text(uuid.uuid4()),
            description=force_text(uuid.uuid4()),
            basket_id=self.basket_id,
        )
        order = create_order(
            self.email,
            self.request,
            shipping_address=self.shipping_address,
            billing_address=self.billing_address,
            shipping_option=rate.name,
        )
        self.assertEqual(order.shipping_rate, amount) 
Example #9
Source File: tests.py    From longclaw with MIT License 6 votes vote down vote up
def test_create_order_with_address_shipping_option(self):
        amount = 12
        rate = ShippingRate.objects.create(
            name=force_text(uuid.uuid4()),
            rate=amount,
            carrier=force_text(uuid.uuid4()),
            description=force_text(uuid.uuid4()),
            destination=self.shipping_address,
        )
        order = create_order(
            self.email,
            self.request,
            shipping_address=self.shipping_address,
            billing_address=self.billing_address,
            shipping_option=rate.name,
        )
        self.assertEqual(order.shipping_rate, amount) 
Example #10
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_options(self, *args):
        """Render only selected options and set QuerySet from :class:`ModelChoiceIterator`."""
        try:
            selected_choices, = args
        except ValueError:
            choices, selected_choices = args
            choices = chain(self.choices, choices)
        else:
            choices = self.choices
        selected_choices = {force_text(v) for v in selected_choices}
        output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
        if isinstance(self.choices, ModelChoiceIterator):
            if self.queryset is None:
                self.queryset = self.choices.queryset
            selected_choices = {c for c in selected_choices
                                if c not in self.choices.field.empty_values}
            choices = [(obj.pk, self.label_from_instance(obj))
                       for obj in self.choices.queryset.filter(pk__in=selected_choices)]
        else:
            choices = [(k, v) for k, v in choices if force_text(k) in selected_choices]
        for option_value, option_label in choices:
            output.append(self.render_option(selected_choices, option_value, option_label))
        return '\n'.join(output) 
Example #11
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def label_from_instance(self, obj):
        """
        Return option label representation from instance.

        Can be overridden to change the representation of each choice.

        Example usage::

            class MyWidget(ModelSelect2Widget):
                def label_from_instance(obj):
                    return force_text(obj.title).upper()

        Args:
            obj (django.db.models.Model): Instance of Django Model.

        Returns:
            str: Option label.

        """
        return force_text(obj) 
Example #12
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_options(self, *args):
        """Render only selected options and set QuerySet from :class:`ModelChoiceIterator`."""
        try:
            selected_choices, = args
        except ValueError:
            choices, selected_choices = args
            choices = chain(self.choices, choices)
        else:
            choices = self.choices
        selected_choices = {force_text(v) for v in selected_choices}
        output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
        if isinstance(self.choices, ModelChoiceIterator):
            if self.queryset is None:
                self.queryset = self.choices.queryset
            selected_choices = {c for c in selected_choices
                                if c not in self.choices.field.empty_values}
            choices = [(obj.pk, self.label_from_instance(obj))
                       for obj in self.choices.queryset.filter(pk__in=selected_choices)]
        else:
            choices = [(k, v) for k, v in choices if force_text(k) in selected_choices]
        for option_value, option_label in choices:
            output.append(self.render_option(selected_choices, option_value, option_label))
        return '\n'.join(output) 
Example #13
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_options(self, *args):
        """Render only selected options and set QuerySet from :class:`ModelChoiceIterator`."""
        try:
            selected_choices, = args
        except ValueError:
            choices, selected_choices = args
            choices = chain(self.choices, choices)
        else:
            choices = self.choices
        selected_choices = {force_text(v) for v in selected_choices}
        output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else '']
        if isinstance(self.choices, ModelChoiceIterator):
            if self.queryset is None:
                self.queryset = self.choices.queryset
            selected_choices = {c for c in selected_choices
                                if c not in self.choices.field.empty_values}
            choices = [(obj.pk, self.label_from_instance(obj))
                       for obj in self.choices.queryset.filter(pk__in=selected_choices)]
        else:
            choices = [(k, v) for k, v in choices if force_text(k) in selected_choices]
        for option_value, option_label in choices:
            output.append(self.render_option(selected_choices, option_value, option_label))
        return '\n'.join(output) 
Example #14
Source File: forms.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def label_from_instance(self, obj):
        """
        Return option label representation from instance.

        Can be overridden to change the representation of each choice.

        Example usage::

            class MyWidget(ModelSelect2Widget):
                def label_from_instance(obj):
                    return force_text(obj.title).upper()

        Args:
            obj (django.db.models.Model): Instance of Django Model.

        Returns:
            str: Option label.

        """
        return force_text(obj) 
Example #15
Source File: views.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def make_rack_statistics(self):
        data = []
        robjects = Rack.objects.filter(onidc_id=self.onidc_id, actived=True)
        keys = Option.objects.filter(
            flag__in=['Rack-Style', 'Rack-Status'],
            actived=True)
        keys = shared_queryset(keys, self.onidc_id)
        for k in keys:
            d = []
            query = {
                k.flag.split('-')[1].lower(): k
            }
            c = robjects.filter(**query).count()
            if c > 0:
                d.append(force_text(k))
                d.append(c)
            if d:
                data.append(d)
        return data 
Example #16
Source File: views.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def make_online_statistics(self):
        data = []
        dobjects = Online.objects.filter(onidc_id=self.onidc_id)
        keys = Option.objects.filter(flag__in=['Device-Style', 'Device-Tags'])
        keys = shared_queryset(keys, self.onidc_id)
        for k in keys:
            d = []
            if k.flag == 'Device-Style':
                c = dobjects.filter(style=k).count()
            else:
                c = dobjects.filter(tags__in=[k]).count()
            if c > 0:
                d.append(force_text(k))
                d.append(c)
            if d:
                data.append(d)
        return data 
Example #17
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_and_save(self, user):
        """
        The main entry point to the sending logic
        """
        from django.utils.encoding import force_text
        messages = list()
        recipients = [r.strip() for r in self.recipient.split(',')]

        for r in recipients:
            try:
                messages.append(self.send_sms(r, user))
            except (ValidationError, IntegrityError), e:
                pass 
Example #18
Source File: test_example.py    From chatterbot-live-example with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_json(self, response):
        return json.loads(force_text(response.content)) 
Example #19
Source File: forms.py    From sentry-auth-saml2 with Apache License 2.0 5 votes vote down vote up
def process_metadata(form_cls, request, helper):
    form = form_cls()

    if 'action_save' not in request.POST:
        return form

    form = form_cls(request.POST)

    if not form.is_valid():
        return form

    try:
        data = form_cls.processor(form)
    except Exception:
        errors = form._errors.setdefault('__all__', ErrorList())
        errors.append('Failed to parse provided SAML2 metadata')
        return form

    saml_form = SAMLForm(data)
    if not saml_form.is_valid():
        field_errors = ['%s: %s' % (k, ', '.join([force_text(i) for i in v])) for k, v in saml_form.errors.items()]
        error_list = ', '.join(field_errors)

        errors = form._errors.setdefault('__all__', ErrorList())
        errors.append(u'Invalid metadata: {}'.format(error_list))
        return form

    helper.bind_state('idp', data)

    # Data is bound, do not respond with a form to signal the nexts steps
    return None 
Example #20
Source File: subadmin_tags.py    From django-subadmin with MIT License 5 votes vote down vote up
def subadmin_breadcrumbs(context):
    request = context['request']
    opts = context['opts']
    root = {
        'name': request.subadmin.root['object']._meta.app_config.verbose_name,
        'url': reverse('admin:app_list', kwargs={'app_label': request.subadmin.root['object']._meta.app_label})
    }
    
    breadcrumbs =[]
    view_args = list(request.subadmin.view_args)

    i = 0
    subadmin_parents = request.subadmin.parents[::-1]

    for parent in subadmin_parents:
        adm = parent['admin']
        obj = parent['object']

        breadcrumbs.extend([{
            'name': obj._meta.verbose_name_plural,
            'url': adm.reverse_url('changelist', *view_args[:i]),
            'has_change_permission': adm.has_change_permission(request),
        }, {
            'name': force_text(obj),
            'url': adm.reverse_url('change', *view_args[:i + 1]),
            'has_change_permission': adm.has_change_permission(request, obj),
        }])
        i += 1
    
    return {
        'root': root,
        'breadcrumbs': breadcrumbs,
        'opts': opts,
    } 
Example #21
Source File: models.py    From django-ads with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return force_text(self.ad) 
Example #22
Source File: models.py    From django-ads with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return force_text(self.ad) 
Example #23
Source File: checker.py    From django-healthchecks with MIT License 5 votes vote down vote up
def _get_basic_auth(request):
    auth = request.META.get('HTTP_AUTHORIZATION')
    if not auth:
        return

    auth = auth.split()
    if len(auth) == 2 and force_text(auth[0]).lower() == u'basic':
        credentials = base64.b64decode(auth[1]).decode('latin-1')
        return tuple(credentials.split(':')) 
Example #24
Source File: storage.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def get_valid_name(self, name):
        """
        Returns a filename, based on the provided filename, that's
        suitable for use in the target storage system.
        """

        name = force_text(name).strip()
        # remove "characters to avoid", as described by S3's and GCP's docs
        # https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html#object-key-guidelines-avoid-characters
        # https://cloud.google.com/storage/docs/naming#objectnames
        name = re.sub(r'[\\{}^%`\[\]<>~#|\x00-\x1F\x7F-\xFF\'"*?]', "", name)
        return re.sub(r"\s+", "_", name) 
Example #25
Source File: models.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        return force_text(self.site) 
Example #26
Source File: gittag.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, value):
        value = force_text(value)
        if value.startswith('http://') or value.startswith('https://'):
            # HTTP(S) URLs: superclass can handle it.
            return super(GitURLValidator, self).__call__(value)

        # or try to validate it as a git scp-style URL
        if not self.ssh_regex.match(value):
            raise ValidationError('Enter a valid "http://", "https://", or "user@host:path" URL.') 
Example #27
Source File: widgets.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def render(self, name, value, attrs=None, renderer=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
        }
        template = '%(input)s'
        substitutions['input'] = super(NotClearableFileInput, self).render(name, value, attrs=attrs, renderer=renderer)

        if value:
            template = self.template_with_initial
            substitutions['initial'] = format_html(force_text(os.path.basename(value.name)))

        return mark_safe(template % substitutions) 
Example #28
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean(self, value):
        super(CAPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return ''
        value = re.sub('(\(|\)|\s+)', '', force_text(value))
        m = phone_digits_re.search(value)
        if m:
            return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))
        raise forms.ValidationError(self.error_messages['invalid']) 
Example #29
Source File: dashboard.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def get_title(self):
        return self.title % force_text(self.obj) 
Example #30
Source File: dashboard.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def init_request(self, object_id, *args, **kwargs):
        self.obj = self.get_object(unquote(object_id))

        if not self.has_view_permission(self.obj):
            raise PermissionDenied

        if self.obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') %
                          {'name': force_text(self.opts.verbose_name), 'key': escape(object_id)})