Python django.utils.encoding.force_unicode() Examples
The following are 30
code examples of django.utils.encoding.force_unicode().
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: utils.py From waliki with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_slug(text): def slugify(value): """ same than django slugify but allowing uppercase and underscore """ value = force_text(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s\/_-]', '', value).strip() return mark_safe(re.sub('[-\s]+', '-', value)) if PY2: from django.utils.encoding import force_unicode text = force_unicode(text) for sep in ('_', '/'): text = sep.join(slugify(t) for t in text.split(sep)) return text.strip('/')
Example #2
Source File: whoosh_cn_backend.py From thirtylol with MIT License | 6 votes |
def _from_python(self, value): """ Converts Python values to a string for Whoosh. Code courtesy of pysolr. """ if hasattr(value, 'strftime'): if not hasattr(value, 'hour'): value = datetime(value.year, value.month, value.day, 0, 0, 0) elif isinstance(value, bool): if value: value = 'true' else: value = 'false' elif isinstance(value, (list, tuple)): value = u','.join([force_text(v) for v in value]) elif isinstance(value, (six.integer_types, float)): # Leave it alone. pass else: value = force_text(value) return value
Example #3
Source File: admin.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _format_callback(self, obj, user, admin_site, perms_needed): has_admin = obj.__class__ in admin_site._registry opts = obj._meta if has_admin: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) p = '%s.%s' % (opts.app_label, get_delete_permission(opts)) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe('%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return '%s: %s' % (capfirst(opts.verbose_name), force_text(obj))
Example #4
Source File: admin.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _list_all_destination_folders_recursive(self, request, folders_queryset, current_folder, folders, allow_self, level): for fo in folders: if not allow_self and fo in folders_queryset: # We do not allow moving to selected folders or their # descendants continue if not fo.has_read_permission(request): continue # We do not allow copying/moving back to the folder itself enabled = ( allow_self or fo != current_folder) and fo.has_add_children_permission(request) yield (fo, (mark_safe((" " * level) + force_text(fo)), enabled)) for c in self._list_all_destination_folders_recursive(request, folders_queryset, current_folder, fo.media_folder_children.all(), allow_self, level + 1): yield c
Example #5
Source File: handlers.py From django-project with BSD 3-Clause "New" or "Revised" License | 6 votes |
def commented_handler(instance, comment, **kwargs): for follow in Follow.objects.get_follows(instance): notify.send(instance.author, recipient=follow.user, actor=instance.author, verb='commented', action_object=comment, description=comment.comment[:50]+'...', target=instance) from django.contrib.contenttypes.models import ContentType from django.contrib.admin.models import LogEntry, ADDITION from django.utils.encoding import force_unicode LogEntry.objects.log_action( user_id = instance.author.pk, content_type_id = ContentType.objects.get_for_model(comment).pk, object_id = comment.pk, object_repr = force_unicode(comment), action_flag = ADDITION ) # connect the signal
Example #6
Source File: list.py From ImitationTmall_Django with GNU General Public License v3.0 | 6 votes |
def get_context(self): """ Prepare the context for templates. """ self.title = _('%s List') % force_unicode(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_unicode(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 #7
Source File: delete.py From ImitationTmall_Django with GNU General Public License v3.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_unicode(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: delete.py From ImitationTmall_Django with GNU General Public License v3.0 | 6 votes |
def get_context(self): if self.perms_needed or self.protected: title = _("Cannot delete %(name)s") % {"name": force_unicode(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 #9
Source File: detail.py From ImitationTmall_Django with GNU General Public License v3.0 | 6 votes |
def get_context(self): new_context = { 'title': _('%s Detail') % force_unicode(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 #10
Source File: util.py From ImitationTmall_Django with GNU General Public License v3.0 | 6 votes |
def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_unicode(opts.verbose_name), 'verbose_name_plural': force_unicode(opts.verbose_name_plural) }
Example #11
Source File: exceptions.py From canvas with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, message, code=None, params=None): """ ValidationError can be passed any object that can be printed (usually a string), or a dictionary. """ import operator from django.utils.encoding import force_unicode if isinstance(message, dict): self.message_dict = message self.messages = [] # Reduce each list of messages into a single list. if message: message = reduce(operator.add, message.values()) self.messages = [force_unicode(msg) for msg in message] else: self.code = code self.params = params message = force_unicode(message) self.messages = [message]
Example #12
Source File: models.py From django-usersettings2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __str__(self): return force_text(self.site)
Example #13
Source File: serializers.py From django-admino with MIT License | 5 votes |
def obj_as_dict(o): if isinstance(o, DeclarativeFieldsMetaclass): o = FormSerializer(form=o).data if isinstance(o, forms.Field): o = FormFieldSerializer(field=o).data if isinstance(o, forms.Widget): o = FormWidgetSerializer(widget=o).data if isinstance(o, (list, tuple)): o = [obj_as_dict(x) for x in o] if isinstance(o, Promise): try: o = force_unicode(o) except: # Item could be a lazy tuple or list try: o = [obj_as_dict(x) for x in o] except: raise Exception('Unable to resolve lazy object %s' % o) if callable(o): o = o() if isinstance(o, dict): for k, v in o.items(): o[k] = obj_as_dict(v) return o
Example #14
Source File: whoosh_cn_backend.py From thirtylol with MIT License | 5 votes |
def create_spelling_suggestion(self, query_string): spelling_suggestion = None reader = self.index.reader() corrector = reader.corrector(self.content_field_name) cleaned_query = force_text(query_string) if not query_string: return spelling_suggestion # Clean the string. for rev_word in self.RESERVED_WORDS: cleaned_query = cleaned_query.replace(rev_word, '') for rev_char in self.RESERVED_CHARACTERS: cleaned_query = cleaned_query.replace(rev_char, '') # Break it down. query_words = cleaned_query.split() suggested_words = [] for word in query_words: suggestions = corrector.suggest(word, limit=1) if len(suggestions) > 0: suggested_words.append(suggestions[0]) spelling_suggestion = ' '.join(suggested_words) return spelling_suggestion
Example #15
Source File: whoosh_cn_backend.py From thirtylol with MIT License | 5 votes |
def _convert_datetime(self, date): if hasattr(date, 'hour'): return force_text(date.strftime('%Y%m%d%H%M%S')) else: return force_text(date.strftime('%Y%m%d000000'))
Example #16
Source File: admin.py From django-radio with GNU General Public License v3.0 | 5 votes |
def clone_calendar(self, request, queryset): for obj in queryset: obj_copy = copy.copy(obj) obj_copy.id = None obj_copy.pk = None copy_name = _('Copy of ') + obj.name obj_copy.name = copy_name obj_copy.is_active = False try: if Calendar.objects.get(name=copy_name): self.message_user( request, _('A calendar with the name %(obj)s already exists') % {'obj': force_unicode(obj)}, level=messages.ERROR ) except Calendar.DoesNotExist: obj_copy.save() # Live schedules have to be created first because we are linking to those objects schedules = [] schedules.extend(Schedule.objects.filter(calendar=obj, type='L')) schedules.extend(Schedule.objects.filter(calendar=obj).exclude(type='L')) for schedule in schedules: schedule_copy = copy.copy(schedule) schedule_copy.id = schedule_copy.pk = None schedule_copy.calendar = obj_copy if schedule_copy.source: source = schedule_copy.source # We should have created the referenced object first # Only live schedules should be in the source field schedule_copy.source = Schedule.objects.get( calendar=obj_copy, start_dt=source.start_dt, type=source.type, programme=source.programme ) schedule_copy.save()
Example #17
Source File: admin.py From django-radio with GNU General Public License v3.0 | 5 votes |
def response_change(self, request, obj): msg = _('%(obj)s was changed successfully.') % {'obj': force_unicode(obj)} if '_continue' in request.POST: self.message_user(request, msg) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) return HttpResponseRedirect("../../")
Example #18
Source File: admin.py From django-radio with GNU General Public License v3.0 | 5 votes |
def response_change(self, request, obj): msg = _('%(obj)s was changed successfully.') % {'obj': force_unicode(obj)} if '_continue' in request.POST: # self.message_user(request, msg + ' ' + _('You may edit it again below.')) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) return HttpResponseRedirect("../../")
Example #19
Source File: utils.py From opensurfaces with MIT License | 5 votes |
def get_upload_dir(obj, attr, time=None): """ Returns the directory used to save obj.attr files """ if not time: time = datetime.datetime.now() upload_to = obj._meta.get_field(attr).upload_to return os.path.normpath(force_unicode( datetime.datetime.now().strftime(smart_str(upload_to))))
Example #20
Source File: conf.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def process_docstring(app, what, name, obj, options, lines): # This causes import errors if left outside the function from django.db import models # Only look at objects that inherit from Django's base model class if inspect.isclass(obj) and issubclass(obj, models.Model): # Ignore abstract models if not hasattr(obj._meta, 'fields'): return lines # Grab the field list from the meta class fields = obj._meta.fields for field in fields: # Decode and strip any html out of the field's help text if hasattr(field, 'help_text'): help_text = strip_tags(force_unicode(field.help_text)) else: help_text = None # Decode and capitalize the verbose name, for use if there isn't # any help text if hasattr(field, 'verbose_name'): verbose_name = force_unicode(field.verbose_name).capitalize() else: verbose_name = "" if help_text: # Add the model field to the end of the docstring as a param # using the help text as the description lines.append(u':param %s: %s' % (field.attname, help_text)) else: # Add the model field to the end of the docstring as a param # using the verbose name as the description lines.append(u':param %s: %s' % (field.attname, verbose_name)) # Add the field's type to the docstring lines.append(u':type %s: %s' % (field.attname, type(field).__name__)) # Return the extended docstring return lines
Example #21
Source File: adapters.py From django-invitations with GNU General Public License v3.0 | 5 votes |
def format_email_subject(self, subject): prefix = app_settings.EMAIL_SUBJECT_PREFIX if prefix is None: site = Site.objects.get_current() prefix = "[{name}] ".format(name=site.name) return prefix + force_text(subject)
Example #22
Source File: mixins.py From django-mmc with GNU General Public License v2.0 | 5 votes |
def __mmc_get_stdout(self): if hasattr(sys.stdout, 'get_stdout'): try: return u''.join(map(force_unicode, sys.stdout.get_stdout())) except: return repr(sys.stdout.get_stdout()) return ''
Example #23
Source File: raw.py From legco-watch with MIT License | 5 votes |
def __unicode__(self): if self.asker_id is None: return u'{}: {} on {}'.format(self.uid, force_unicode(self.raw_asker), force_unicode(self.raw_date)) else: return u'{}: {} on {}'.format(self.uid, force_unicode(self.asker), force_unicode(self.raw_date))
Example #24
Source File: adapter.py From django-actistream with MIT License | 5 votes |
def format_email_subject(self, subject): prefix = getattr(settings, 'ACTISTREAM_EMAIL_SUBJECT_PREFIX', None) if prefix is None: site = self.get_current_site() if site: prefix = "[{name}] ".format(name=site.name) else: prefix = '' return prefix + force_text(subject)
Example #25
Source File: dashboard.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def render(self, name, value, attrs=None): if value is None: value = '' 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_unicode(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_unicode(value))) return mark_safe(u'\n'.join(output))
Example #26
Source File: dashboard.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def get_title(self): return self.title % force_unicode(self.obj)
Example #27
Source File: dashboard.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
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_unicode(self.opts.verbose_name), 'key': escape(object_id)})
Example #28
Source File: list.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def label(self): text = mark_safe( self.text) if self.allow_tags else conditional_escape(self.text) if force_unicode(text) == '': text = mark_safe(' ') for wrap in self.wraps: text = mark_safe(wrap % text) return text
Example #29
Source File: delete.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def get_breadcrumb(self): bcs = super(DeleteAdminView, self).get_breadcrumb() bcs.append({ 'title': force_unicode(self.obj), 'url': self.get_object_url(self.obj) }) item = {'title': _('Delete')} if self.has_delete_permission(): item['url'] = self.model_admin_url('delete', self.obj.pk) bcs.append(item) return bcs
Example #30
Source File: delete.py From ImitationTmall_Django with GNU General Public License v3.0 | 5 votes |
def post_response(self): self.message_user(_('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_unicode(self.opts.verbose_name), 'obj': force_unicode(self.obj)}, 'success') if not self.has_view_permission(): return self.get_admin_url('index') return self.model_admin_url('changelist')