我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.contrib.admin.utils.quote()。
def get_geo(address): result = (None, None) if address.replace(',', '').strip(): address = quote(address.lower().encode("utf-8")) sensor = "false" url = '{url}?address={address}&sensor={sensor}'.format(url=settings.GOOGLE_GEOCODE_ENDPOINT, address=address, sensor=sensor) response = requests.get(url) response.raise_for_status() result = response.json() if result['status'] == 'OK': lat = str(result['results'][0]['geometry']['location']['lat']) lng = str(result['results'][0]['geometry']['location']['lng']) result = (lat, lng) else: result = (None, None) return result
def revision_view(self, request, object_id, version_id, extra_context=None): if not is_installed('reversion'): return HttpResponseBadRequest('django reversion not installed') if not self.has_change_permission(request, Page.objects.get(pk=object_id)): raise PermissionDenied page = get_object_or_404(self.model, pk=object_id) if not page.publisher_is_draft: page = page.publisher_draft if not page.has_change_permission(request): return HttpResponseForbidden(force_text(_("You do not have permission to change this page"))) try: version = Version.objects.get(pk=version_id) clean = page._apply_revision(version.revision, set_dirty=True) if not clean: messages.error(request, _("Page reverted but slug stays the same because of url collisions.")) with create_revision(): adapter = self.revision_manager.get_adapter(page.__class__) self.revision_context_manager.add_to_context(self.revision_manager, page, adapter.get_version_data(page)) self.revision_context_manager.set_comment(_("Reverted to previous version, saved on %(datetime)s") % {"datetime": localize(version.revision.date_created)}) except IndexError as e: return HttpResponseBadRequest(e.message) return HttpResponseRedirect(admin_reverse('cms_page_change', args=(quote(object_id),)))
def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): if exclude is None: exclude = [] if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] ph = self.permission_helper usr = self.request.user pk = quote(getattr(obj, self.opts.pk.attname)) btns = [] if ph.user_can_inspect_obj(usr, obj): btns.append(self.detail_button( pk, classnames_add, classnames_exclude)) btns.append(self.cancel_button( pk, classnames_add, classnames_exclude)) return btns
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. """ if self.content_type and self.object_id: url_name = 'admin:%s_%s_change' % (self.content_type.app_label, self.content_type.model) try: return reverse(url_name, args=(quote(self.object_id),)) except NoReverseMatch: pass return None
def admin_urlquote(value): return quote(value)
def report_button(self, pk, classnames_add=[], classnames_exclude=[]): classnames = classnames_add cn = self.finalise_classname(classnames, classnames_exclude) return { 'url': reverse('experiments:report', args=(quote(pk), )), 'label': _('Show report'), 'classname': cn, 'title': _('Report for this %s') % self.verbose_name, }
def get_buttons_for_obj(self, obj, exclude=[], classnames_add=[], classnames_exclude=[]): ph = self.permission_helper pk = quote(getattr(obj, self.opts.pk.attname)) btns = super(ExperimentButtonHelper, self).get_buttons_for_obj(obj, exclude, classnames_add, classnames_exclude) if 'report' not in exclude and ph.user_can_edit_obj(self.request.user, obj): btns.append( self.report_button(pk, classnames_add, classnames_exclude) ) return btns
def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( 'admin:%s_%s_change' % (result._meta.app_label, result._meta.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name )
def url_for_result(self, result): pk_attname = result._meta.pk.attname pk = getattr(result, pk_attname) return reverse('admin:%s_%s_change' % (result._meta.app_label, result._meta.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name)
def admin_foreign_key_link(field): def decorator(func): @wraps(func) def wrapper(self, obj): result = func(self, obj) if result: # if function return something, we do nothing and just return; return result # most of the cases will trigger this ELSE branch; from django.template import Context, Template from django.core.urlresolvers import reverse from django.contrib.admin.utils import quote assert hasattr(obj, field) _field_attr = getattr(obj, field, None) if _field_attr is None: _django_template = Template('') _context = Context() else: _description = '{{name}} {{id}}' _str_template = '<a href="{{url}}">%s</a>' % _description _django_template = Template(_str_template) _pk_value = _field_attr.id url = reverse( 'admin:%s_%s_change' % (_field_attr.__class__._meta.app_label, _field_attr.__class__.__name__.lower()), args=(quote(_pk_value),), current_app=self.admin_site.name, ) _context = Context({'url': url, 'name': _field_attr.__class__._meta.verbose_name.title(), 'id': _pk_value }) return _django_template.render(_context) return wrapper return decorator
def approve_button(self, pk, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] classnames = self.edit_button_classnames + classnames_add cn = self.finalise_classname(classnames, classnames_exclude) return { 'url': self.url_helper.get_action_url('approve', quote(pk)), 'label': _('Approve'), 'classname': cn, 'title': _('Approve applicants for %s') % self.verbose_name, }
def appoint_button(self, pk, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] classnames = self.edit_button_classnames + classnames_add cn = self.finalise_classname(classnames, classnames_exclude) return { 'url': self.url_helper.get_action_url('appoint', quote(pk)), 'label': _('Appoint'), 'classname': cn, 'title': _('Appoint member to %s') % self.verbose_name, }
def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): btns = [] if exclude is None: exclude = [] if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] ph = self.permission_helper usr = self.request.user pk = quote(getattr(obj, self.opts.pk.attname)) if 'approve' not in exclude and approve_state(usr, obj)\ and ph.user_can_approve_obj(usr, obj): btns.append( self.approve_button( pk, classnames_add, classnames_exclude ) ) if 'appoint' not in exclude and appoint_state(usr, obj)\ and ph.user_can_appoint_obj(usr, obj): btns.append( self.appoint_button( pk, classnames_add, classnames_exclude ) ) btns += super(PositionButtonHelper, self).get_buttons_for_obj( obj, exclude=exclude, classnames_add=classnames_add, classnames_exclude=classnames_exclude ) return btns
def change_view(self, request, object_id, form_url='', extra_context=None): """ The 'change' admin view for the Page model. """ if extra_context is None: extra_context = {'basic_info': True} try: obj = self.model.objects.get(pk=object_id) except self.model.DoesNotExist: # Don't raise Http404 just yet, because we haven't checked # permissions yet. We don't want an unauthenticated user to be able # to determine whether a given object exists. obj = None else: context = { 'page': obj, 'CMS_PERMISSION': get_cms_setting('PERMISSION'), 'ADMIN_MEDIA_URL': settings.STATIC_URL, 'can_change': obj.has_change_permission(request), 'can_change_permissions': obj.has_change_permissions_permission(request), 'current_site_id': settings.SITE_ID, } context.update(extra_context or {}) extra_context = self.update_language_tab_context(request, obj, context) tab_language = get_language_from_request(request) extra_context.update(self.get_unihandecode_context(tab_language)) response = super(PageAdmin, self).change_view( request, object_id, form_url=form_url, extra_context=extra_context) if tab_language and response.status_code == 302 and response._headers['location'][1] == request.path_info: location = response._headers['location'] response._headers['location'] = (location[0], "%s?language=%s" % (location[1], tab_language)) if request.method == "POST" and response.status_code in (200, 302): if 'history' in request.path_info: return HttpResponseRedirect(admin_reverse('cms_page_change', args=(quote(object_id),))) elif 'recover' in request.path_info: return HttpResponseRedirect(admin_reverse('cms_page_change', args=(quote(object_id),))) return response
def test_thread_delete_view__get__success(self, _, __): thread_data = THREADS_LIST_RESPONSE['response'][0] post_data = POSTS_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) related_post_object = post_factory(post_data) related_post_object.thread = thread_object delete_url = reverse('{admin_site_name}:{app_label}_{model_name}_delete'.format( admin_site_name=admin.site.name, app_label=Thread._meta.app_label, model_name=Thread._meta.model_name ), args=[thread_object.id]) request = RequestFactory().get(delete_url, follow=True) request.user = MockSuperUser() response = ThreadAdmin(Thread, admin.site).delete_view(request, str(thread_object.id)) template_names = set([ 'admin/delete_confirmation.html', 'admin/disqus_backstore/delete_confirmation.html', 'admin/disqus_backstore/thread/delete_confirmation.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) # dirty hack for formatting deleted_object context... Use the same formatting # in django.contrib.admin.utils.get_deleted_objects # the related post objects will be a list of post object, # so we have to put it into a list... deleted_objects = [format_html('{}: <a href="{}">{}</a>', capfirst(obj.__class__._meta.verbose_name), reverse('%s:%s_%s_change' % ( admin.site.name, obj._meta.app_label, obj._meta.model_name ), None, (quote(obj._get_pk_val()),)), obj) for obj in [thread_object, related_post_object]] deleted_objects[1] = [deleted_objects[1]] self.assertEqual(sorted(response.context_data['deleted_objects']), sorted(deleted_objects))
def test_post_delete_view__get__success(self, _, __): thread_data = THREADS_LIST_RESPONSE['response'][0] post_data = POSTS_LIST_RESPONSE['response'][0] thread_object = thread_factory(thread_data) post_object = post_factory(post_data) post_object.thread = thread_object delete_url = reverse('{admin_site_name}:{app_label}_{model_name}_delete'.format( admin_site_name=admin.site.name, app_label=Post._meta.app_label, model_name=Post._meta.model_name ), args=[post_data['id']]) request = RequestFactory().get(delete_url, follow=True) request.user = MockSuperUser() response = PostAdmin(Post, admin.site).delete_view(request, post_data['id']) template_names = set([ 'admin/delete_confirmation.html', 'admin/disqus_backstore/delete_confirmation.html', 'admin/disqus_backstore/post/delete_confirmation.html', ]) self.assertEqual(response.status_code, 200) self.assertEqual(set(response.template_name), template_names) # dirty hack for formatting deleted_object context... Use the same formatting # in django.contrib.admin.utils.get_deleted_objects deleted_objects = [format_html('{}: <a href="{}">{}</a>', capfirst(obj.__class__._meta.verbose_name), reverse('%s:%s_%s_change' % ( admin.site.name, obj._meta.app_label, obj._meta.model_name ), None, (quote(obj._get_pk_val()),)), obj) for obj in [post_object]] self.assertEqual(response.context_data['deleted_objects'], deleted_objects)
def detail_button(self, pk, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = ['detail-button'] if classnames_exclude is None: classnames_exclude = [] classnames = self.detail_button_classnames + classnames_add cn = self.finalise_classname(classnames, classnames_exclude) return { 'url': self.url_helper.get_action_url('detail', quote(pk)), 'label': _('View'), 'classname': cn, 'title': _('View this %s') % self.verbose_name, }