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: list.py From StormOnline with Apache License 2.0 | 6 votes |
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 #2
Source File: delete.py From StormOnline with Apache License 2.0 | 6 votes |
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 #3
Source File: dashboard.py From StormOnline with Apache License 2.0 | 6 votes |
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: rest.py From coursys with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: tests.py From longclaw with MIT License | 6 votes |
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 #6
Source File: tests.py From longclaw with MIT License | 6 votes |
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 #7
Source File: delete.py From StormOnline with Apache License 2.0 | 6 votes |
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 #8
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #10
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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: detail.py From StormOnline with Apache License 2.0 | 6 votes |
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 #12
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 |
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 #14
Source File: widgets.py From django-fontawesome with BSD 2-Clause "Simplified" License | 6 votes |
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 #15
Source File: views.py From django-idcops with Apache License 2.0 | 6 votes |
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 |
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: ajax.py From StormOnline with Apache License 2.0 | 5 votes |
def get_result_list(self, response): av = self.admin_view base_fields = self.get_list_display(av.base_list_display) headers = dict([(c.field_name, force_text(c.text)) for c in av.result_headers( ).cells if c.field_name in base_fields]) objects = [dict([(o.field_name, escape(str(o.value))) for i, o in enumerate(filter(lambda c:c.field_name in base_fields, r.cells))]) for r in av.results()] return self.render_response({'headers': headers, 'objects': objects, 'total_count': av.result_count, 'has_more': av.has_more})
Example #18
Source File: forms.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def render_options(self, *args): """Render only selected options.""" try: selected_choices, = args except ValueError: # Signature contained `choices` prior to Django 1.10 choices, selected_choices = args choices = chain(self.choices, choices) else: choices = self.choices output = ['<option></option>' if not self.is_required and not self.allow_multiple_selected else ''] selected_choices = {force_text(v) for v in selected_choices} 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 #19
Source File: export.py From StormOnline with Apache License 2.0 | 5 votes |
def _get_objects(self, context): headers = [c for c in context['result_headers'].cells if c.export] rows = context['results'] return [dict([ (force_text(headers[i].text), self._format_value(o)) for i, o in enumerate(filter(lambda c:getattr(c, 'export', False), r.cells))]) for r in rows]
Example #20
Source File: export.py From StormOnline with Apache License 2.0 | 5 votes |
def _get_datas(self, context): rows = context['results'] new_rows = [[self._format_value(o) for o in filter(lambda c:getattr(c, 'export', False), r.cells)] for r in rows] new_rows.insert(0, [force_text(c.text) for c in context['result_headers'].cells if c.export]) return new_rows
Example #21
Source File: export.py From StormOnline with Apache License 2.0 | 5 votes |
def get_xlsx_export(self, context): datas = self._get_datas(context) output = io.BytesIO() export_header = ( self.request.GET.get('export_xlsx_header', 'off') == 'on') model_name = self.opts.verbose_name book = xlsxwriter.Workbook(output) sheet = book.add_worksheet( u"%s %s" % (_(u'Sheet'), force_text(model_name))) styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}), 'date': book.add_format({'num_format': 'yyyy-mm-dd'}), 'time': book.add_format({'num_format': 'hh:mm:ss'}), 'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}), 'default': book.add_format()} if not export_header: datas = datas[1:] for rowx, row in enumerate(datas): for colx, value in enumerate(row): if export_header and rowx == 0: cell_style = styles['header'] else: if isinstance(value, datetime.datetime): cell_style = styles['datetime'] elif isinstance(value, datetime.date): cell_style = styles['date'] elif isinstance(value, datetime.time): cell_style = styles['time'] else: cell_style = styles['default'] sheet.write(rowx, colx, value, cell_style) book.close() output.seek(0) return output.getvalue()
Example #22
Source File: xversion.py From StormOnline with Apache License 2.0 | 5 votes |
def get_context(self): context = super(RevisionListView, self).get_context() opts = self.opts action_list = [ { "revision": version.revision, "url": self.model_admin_url('revision', quote(version.object_id), version.id), "version": version } for version in self._reversion_order_version_queryset(Version.objects.get_for_object_reference( self.model, self.obj.pk, ).select_related("revision__user")) ] context.update({ 'title': _('Change history: %s') % force_text(self.obj), 'action_list': action_list, 'model_name': capfirst(force_text(opts.verbose_name_plural)), 'object': self.obj, 'app_label': opts.app_label, "changelist_url": self.model_admin_url("changelist"), "update_url": self.model_admin_url("change", self.obj.pk), 'opts': opts, }) return context
Example #23
Source File: relate.py From StormOnline with Apache License 2.0 | 5 votes |
def get_brand_name(self): if len(self.to_objs) == 1: to_model_name = str(self.to_objs[0]) else: to_model_name = force_text(self.to_model._meta.verbose_name) return mark_safe(u"<span class='rel-brand'>%s <i class='fa fa-caret-right'></i></span> %s" % (to_model_name, force_text(self.opts.verbose_name_plural)))
Example #24
Source File: relate.py From StormOnline with Apache License 2.0 | 5 votes |
def related_link(self, instance): links = [] for rel, view_perm, add_perm in self.get_related_list(): opts = rel.related_model._meta label = opts.app_label model_name = opts.model_name field = rel.field rel_name = rel.get_related_field().name verbose_name = force_text(opts.verbose_name) lookup_name = '%s__%s__exact' % (field.name, rel_name) link = ''.join(('<li class="with_menu_btn">', '<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' % ( reverse('%s:%s_%s_changelist' % ( self.admin_site.app_name, label, model_name)), RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else '<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name, '<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' % ( reverse('%s:%s_%s_add' % ( self.admin_site.app_name, label, model_name)), RELATE_PREFIX + lookup_name, str( instance.pk)) if add_perm else "", '</li>')) links.append(link) ul_html = '<ul class="dropdown-menu" role="menu">%s</ul>' % ''.join( links) return '<div class="dropdown related_menu pull-right"><a title="%s" class="relate_menu dropdown-toggle" data-toggle="dropdown"><i class="icon fa fa-list"></i></a>%s</div>' % (_('Related Objects'), ul_html)
Example #25
Source File: editable.py From StormOnline with Apache License 2.0 | 5 votes |
def init_request(self, object_id, *args, **kwargs): self.org_obj = self.get_object(unquote(object_id)) # For list view get new field display html self.pk_attname = self.opts.pk.attname if not self.has_change_permission(self.org_obj): raise PermissionDenied if self.org_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)})
Example #26
Source File: multiselect.py From StormOnline with Apache License 2.0 | 5 votes |
def render_opt(self, selected_choices, option_value, option_label): option_value = force_text(option_value) return u'<option value="%s">%s</option>' % ( escape(option_value), conditional_escape(force_text(option_label))), bool(option_value in selected_choices)
Example #27
Source File: xversion.py From StormOnline with Apache License 2.0 | 5 votes |
def post_response(self): self.message_user(_('The %(model)s "%(name)s" was recovered successfully. You may edit it again below.') % {"model": force_text(self.opts.verbose_name), "name": smart_text(self.new_obj)}, 'success') return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))
Example #28
Source File: xversion.py From StormOnline with Apache License 2.0 | 5 votes |
def post_response(self): self.message_user(_('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_text(self.opts.verbose_name), "name": smart_text(self.new_obj)}, 'success') return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))
Example #29
Source File: xversion.py From StormOnline with Apache License 2.0 | 5 votes |
def get_context(self): context = super(RevisionView, self).get_context() context["title"] = _( "Revert %s") % force_text(self.model._meta.verbose_name) return context
Example #30
Source File: test_example.py From chatterbot-live-example with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_json(self, response): return json.loads(force_text(response.content))