我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.encoding.force_unicode()。
def render(self, name, value, attrs=None): # Prepare values attrs = self.build_attrs(attrs, name=name) if not value: value = '' options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {}) if 'options' in attrs: options = self._eval_value(attrs['options'], {}) del attrs['options'] # Render widget to HTML t = loader.get_template('markedit/ui.html') c = Context({ 'attributes': self._render_attrs(attrs), 'value': conditional_escape(force_unicode(value)), 'id': attrs['id'], 'options': options, }) return t.render(c)
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)
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
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) }
def process_email(email): """Validates that the email is valid. Return email ascii encoded if valid, None if not. """ if not email: return None email = force_unicode(email) try: # NOTE SFDC doesn't support SMPTUTF8, so we cannot enable support # here until they do or we switch providers info = validate_email(email, allow_smtputf8=False, check_deliverability=False) except EmailNotValidError: return None return info.get('email_ascii', None)
def render(self, name, value, attrs=None): if value is None: value = "" if VERSION < (1, 11): final_attrs = self.build_attrs(attrs, name=name) else: final_attrs = self.build_attrs(attrs, {'name': name}) if "class" not in final_attrs: final_attrs["class"] = "" final_attrs["class"] += " wmd-input" template = loader.get_template(self.template) # Compatibility fix: # see https://github.com/timmyomahony/django-pagedown/issues/42 context = { "attrs": flatatt(final_attrs), "body": conditional_escape(force_unicode(value)), "id": final_attrs["id"], "show_preview": self.show_preview, } context = Context(context) if VERSION < (1, 9) else context return template.render(context)
def serialize_instance(instance): """ Since Django 1.6 items added to the session are no longer pickled, but JSON encoded by default. We are storing partially complete models in the session (user, account, token, ...). We cannot use standard Django serialization, as these are models are not "complete" yet. Serialization will start complaining about missing relations et al. """ data = {} for k, v in instance.__dict__.items(): if k.startswith('_') or callable(v): continue try: if isinstance(instance._meta.get_field(k), BinaryField): v = force_text(base64.b64encode(v)) except FieldDoesNotExist: pass data[k] = v return json.loads(json.dumps(data, cls=DjangoJSONEncoder))
def get_context(self): """ **Context Params**: ``title`` : ???? ``object_id`` : ???????? id """ new_context = { 'title': _('Change %s') % force_unicode(self.org_obj), 'object_id': str(self.org_obj.pk), 'cl': self } context = super(UpdateAdminView, self).get_context() context.update(new_context) return context
def get_context(self): """ **Context Params** : ``form`` : ??????? Form ?? ``object`` : ???? Model ?? """ 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
def init_request(self, object_id, *args, **kwargs): """ ??????????? ``object_id`` ???????????????????? """ 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) # ????db # ?? deleted_objects, ?????????????? (self.deleted_objects, self.perms_needed, self.protected) = get_deleted_objects( [self.obj], self.opts, self.request.user, self.admin_site, using)
def default(self, obj): if isinstance(obj, bson.objectid.ObjectId): return force_unicode(obj) return super(MongoJSONEncoder, self).default(obj)
def text_value(value): """ Force a value to text, render None as an empty string """ if value is None: return '' return force_text(value)
def by_date(instance, filename): datepart = force_text(now().strftime("%Y/%m/%d")) return os.path.join(datepart, get_valid_filename(filename))
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
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(PootleJSONEncoder, self).default(obj) except TypeError: return force_unicode(obj)
def handle_exception(request, exception, template_name): # XXX: remove this? exceptions are already displayed in debug mode tb = traceback.format_exc() print >> sys.stderr, tb if settings.DEBUG: return None try: log_exception(request, exception, tb) msg = force_unicode(exception) if request.is_ajax(): return JsonResponseServerError({'msg': msg}) ctx = { 'exception': msg, } if hasattr(exception, 'filename'): msg_args = { 'filename': exception.filename, 'errormsg': exception.strerror, } msg = _('Error accessing %(filename)s, Filesystem ' 'sent error: %(errormsg)s', msg_args) ctx['fserror'] = msg return HttpResponseServerError( render_to_string(template_name, context=ctx, request=request) ) except: # Let's not confuse things by throwing an exception here pass
def process_exception(self, request, exception): msg = force_unicode(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')
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)
def render(self, name=None, value=None, attrs=None, choices=()): name = name or self.name value = value or self.value attrs = attrs or self.attrs attrs['class'] = attrs.get('class', '').replace('form-control', '') if 'id' in self.attrs: label_for = ' for="%s_%s"' % (self.attrs['id'], self.index) else: label_for = '' choice_label = conditional_escape(force_unicode(self.choice_label)) if attrs.get('inline', False): return mark_safe(u'<label%s class="radio-inline">%s %s</label>' % (label_for, self.tag(), choice_label)) else: return mark_safe(u'<div class="radio"><label%s>%s %s</label></div>' % (label_for, self.tag(), choice_label))
def render(self): return mark_safe(u'\n'.join([force_unicode(w) for w in self]))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput( final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) if final_attrs.get('inline', False): output.append(u'<label%s class="checkbox-inline">%s %s</label>' % (label_for, rendered_cb, option_label)) else: output.append(u'<div class="checkbox"><label%s>%s %s</label></div>' % (label_for, rendered_cb, option_label)) return mark_safe(u'\n'.join(output))
def get_context(self): new_context = { 'title': _('Add %s') % force_unicode(self.opts.verbose_name), } context = super(CreateAdminView, self).get_context() context.update(new_context) return context
def get_breadcrumb(self): bcs = super(ModelFormAdminView, self).get_breadcrumb() item = {'title': _('Add %s') % force_unicode(self.opts.verbose_name)} if self.has_add_permission(): item['url'] = self.model_admin_url('add') bcs.append(item) return bcs
def init_request(self, object_id, *args, **kwargs): self.org_obj = self.get_object(unquote(object_id)) 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_unicode(self.opts.verbose_name), 'key': escape(object_id)}) # comm method for both get and post self.prepare_form()
def get_context(self): new_context = { 'title': _('Change %s') % force_unicode(self.org_obj), 'object_id': str(self.org_obj.pk), } context = super(UpdateAdminView, self).get_context() context.update(new_context) return context
def get_breadcrumb(self): bcs = super(ModelFormAdminView, self).get_breadcrumb() item = {'title': force_unicode(self.org_obj)} if self.has_change_permission(): item['url'] = self.model_admin_url('change', self.org_obj.pk) bcs.append(item) return bcs
def post_response(self): """ Determines the HttpResponse for the change_view stage. """ opts = self.new_obj._meta obj = self.new_obj request = self.request verbose_name = opts.verbose_name pk_value = obj._get_pk_val() msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(verbose_name), 'obj': force_unicode(obj)} if "_continue" in request.POST: self.message_user( msg + ' ' + _("You may edit it again below."), 'success') return request.path elif "_addanother" in request.POST: self.message_user(msg + ' ' + (_("You may add another %s below.") % force_unicode(verbose_name)), 'success') return self.model_admin_url('add') else: self.message_user(msg, 'success') # Figure out where to redirect. If the user has change permission, # redirect to the change-list page for this object. Otherwise, # redirect to the admin index. if "_redirect" in request.POST: return request.POST["_redirect"] elif self.has_view_permission(): change_list_url = self.model_admin_url('changelist') if 'LIST_QUERY' in self.request.session \ and self.request.session['LIST_QUERY'][0] == self.model_info: change_list_url += '?' + self.request.session['LIST_QUERY'][1] return change_list_url else: return self.get_admin_url('index')
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
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))
def get_title(self): return self.title % force_unicode(self.obj)
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)})
def val(self): text = mark_safe( self.text) if self.allow_tags else conditional_escape(self.text) if force_unicode(text) == '' or text == 'None' or text == EMPTY_CHANGELIST_VALUE: text = mark_safe( '<span class="text-muted">%s</span>' % EMPTY_CHANGELIST_VALUE) for wrap in self.wraps: text = mark_safe(wrap % text) return text
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)}) self.org_obj = self.obj
def get_breadcrumb(self): bcs = super(DetailAdminView, self).get_breadcrumb() item = {'title': force_unicode(self.obj)} if self.has_view_permission(): item['url'] = self.model_admin_url('detail', self.obj.pk) bcs.append(item) return bcs
def get_context(self): new_context = { "opts": self.opts, "app_label": self.app_label, "model_name": self.model_name, "verbose_name": force_unicode(self.opts.verbose_name), 'model_icon': self.get_model_icon(self.model), } context = super(ModelAdminView, self).get_context() context.update(new_context) return context
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
def get_context(self): context = super(RecoverListView, self).get_context() opts = self.opts deleted = self._order_version_queryset(Version.objects.get_deleted(self.model)) context.update({ "opts": opts, "app_label": opts.app_label, "model_name": capfirst(opts.verbose_name), "title": _("Recover deleted %(name)s") % {"name": force_unicode(opts.verbose_name_plural)}, "deleted": deleted, "changelist_url": self.model_admin_url("changelist"), }) return context
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_unicode(self.obj), 'action_list': action_list, 'model_name': capfirst(force_unicode(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
def get_context(self): context = super(RevisionView, self).get_context() context["title"] = _( "Revert %s") % force_unicode(self.model._meta.verbose_name) return context
def post_response(self): self.message_user(_('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": force_unicode(self.opts.verbose_name), "name": unicode(self.new_obj)}, 'success') return HttpResponseRedirect(self.model_admin_url('change', self.new_obj.pk))