def testAdminUrlsNoClash(self): """ Test that some admin URLs work correctly. """ # Should get the change_view for model instance with PK 'add', not show # the add_view response = self.client.get( '/custom_urls/admin/admin_custom_urls/action/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Ditto, but use reverse() to build the URL url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote('add'), )) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Should correctly get the change_view for the model instance with the # funny-looking PK (the one wth a 'path/to/html/document.html' value) url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote("path/to/html/document.html"), )) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') self.assertContains(response, 'value="path/to/html/document.html"')
def handle_create_node(instance, node_info): pk = quote(getattr(instance, pk_attname)) node_info.update( url=self.get_admin_url('change', (quote(pk),)), move_url=self.get_admin_url('move', (quote(pk),)) )
def testAdminUrlsNoClash(self): """ Test that some admin URLs work correctly. """ # Should get the change_view for model instance with PK 'add', not show # the add_view response = self.client.get('/custom_urls/admin/admin_custom_urls/action/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Ditto, but use reverse() to build the URL url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote('add'),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Should correctly get the change_view for the model instance with the # funny-looking PK (the one wth a 'path/to/html/document.html' value) url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote("path/to/html/document.html"),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') self.assertContains(response, 'value="path/to/html/document.html"')
def test_deleteconfirmation_link(self): "The link from the delete confirmation page referring back to the changeform of the object should be quoted" response = self.client.get( '/test_admin/admin/admin_views/modelwithstringprimarykey/%s/delete/' % quote(self.pk)) should_contain = """<a href="../../%s/">%s</a>""" % (quote( self.pk), escape(self.pk)) self.assertContains(response, should_contain)
def url_for_result(self, result): # Salva: Caso especial para Mac if self.model == Macip: interface = quote(str(getattr(result, 'interface'))) switch = quote(str(getattr(result, 'switch'))) if switch=='None' or interface=='None': return '' return "../interface/%s!!!%s/" % (switch,interface) else: return "%s/" % quote(getattr(result, self.pk_attname))
def get_history_url(model, history_index=None): try: info = model._meta.app_label, model._meta.module_name except AttributeError: info = model._meta.app_label, model._meta.model_name if history_index is not None: history = model.history.order_by('history_id')[history_index] return reverse('admin:%s_%s_simple_history' % info, args=[quote(model.pk), quote(history.history_id)]) else: return reverse('admin:%s_%s_history' % info, args=[quote(model.pk)])
def get_success_url(self): if (self.request.POST.get('_grabar')): url = self._url_a_vista_red() if (self.request.POST.get('_grabar_y_siguiente')): if self.object.siguiente_libre(): GET=self.request.GET.copy() # request.GET es immutable GET['no_peticion']=quote(self.form.cleaned_data['no_peticion']) #IGNORE:no-member GET['notas']=quote(self.form.cleaned_data['notas']) #IGNORE:no-member url = self._url_a_siguiente_ip(GET) else: #Si no quedan IPs libres vuelve a la vista de red url = self._url_a_vista_red() return url
def handle_create_node(instance, node_info): pk = quote(getattr(instance, pk_attname)) node_info.update( url=self.get_admin_url('change', (quote(pk),)), move_url=self.get_admin_url('move', (quote(pk),)), label='<span class="ex-category %(clazz)s %(visible)s">%(label)s <span class="ex-label">%(clazz_display)s</span> <i class="fa fa-eye"></i> <span class="path">%(path)s</span></span>' % { 'label': node_info['label'], 'clazz': instance._meta.object_name.lower(), 'clazz_display': instance._meta.verbose_name, 'visible': 'on' if instance.visible else 'off', 'path': instance.path, } )
def remove(self, obj, **kwargs): """ This will not work without a custom get_list_display like above in this class. """ request = kwargs.pop('request') if self.has_delete_permission(request, obj): info = obj._meta.app_label, obj._meta.module_name delete_url = reverse('admin:%s_%s_delete' % info, args=(quote(obj.pk), quote(self.prescription.pk))) return ('<a href="%s" class="btn btn-mini alert-error" ' 'title="Delete"><i class="icon-trash"></i></a>') % delete_url else: return ""
def get_history_url(obj, history_index=None, site="admin"): try: app, model = obj._meta.app_label, obj._meta.module_name except AttributeError: app, model = obj._meta.app_label, obj._meta.model_name if history_index is not None: history = obj.history.order_by('history_id')[history_index] return reverse( "{site}:{app}_{model}_simple_history".format( site=site, app=app, model=model), args=[quote(obj.pk), quote(history.history_id)], ) else: return reverse("{site}:{app}_{model}_history".format( site=site, app=app, model=model), args=[quote(obj.pk)])
def format_callback(obj): has_admin = admin_site._registry.get(obj.__class__, False) opts = obj._meta if has_admin: if getattr(has_admin, 'deletable_objects_excluded', False): return '' 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, opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. # NOTE: Define as unicode for avoid errors when obj # representation contains non-ascii chars return format_html(u'{0}: <a href="{1}">{2}</a>', capfirst(opts.verbose_name), admin_url, obj) else: # Don't display link to edit, because it either has no # admin or is edited inline. return u'%s: %s' % (capfirst(opts.verbose_name), force_text(obj))
def test_balloons_link_and_cookie(self): self.client.login(username='******') regenerate_url = reverse('balloons_access_regenerate', kwargs={'contest_id': self.contest.id}) response = self.client.post(regenerate_url) self.assertEqual(response.status_code, 403) self.client.login(username='******') regenerate_url = reverse('balloons_access_regenerate', kwargs={'contest_id': self.contest.id}) response = self.client.post(regenerate_url) self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith( reverse('oioioiadmin:contests_contest_change', args=[quote(self.contest.id)]) )) self.client.logout() access_data = BalloonsDeliveryAccessData.objects.get() set_cookie_url = reverse('balloons_access_set_cookie', kwargs={'contest_id': self.contest.id, 'access_key': access_data.access_key}) panel_url = reverse('balloons_delivery_panel', kwargs=self.c_kwargs) cookie_key = 'balloons_access_' + self.contest.id response = self.client.get(set_cookie_url) self.assertEqual(response.status_code, 302) self.assertTrue(response['Location'].endswith(panel_url)) self.assertTrue(cookie_key in response.cookies) self.assertEqual(response.cookies[cookie_key].value, access_data.access_key)
def Comments(request, app, model, object_id): try: modeltype = ContentType.objects.using(request.database).get(app_label=app, model=model) modeltype._state.db = request.database object_id = unquote(object_id) modelinstance = modeltype.get_object_for_this_type(pk=object_id) comments = Comment.objects.using(request.database) \ .filter(content_type__pk=modeltype.id, object_pk=object_id) \ .order_by('-id') except: raise Http404('Object not found') if request.method == 'POST': comment = request.POST['comment'] if comment: request.user._state.db = request.database # Need to lie a bit Comment( content_object=modelinstance, user=request.user, comment=comment ).save(using=request.database) return HttpResponseRedirect('%s/comments/%s/%s/%s/' % (request.prefix, app, model, object_id)) else: return render_to_response('common/comments.html', { 'title': capfirst(force_unicode(modelinstance._meta.verbose_name) + " " + object_id), 'model': model, 'object_id': quote(object_id), 'active_tab': 'comments', 'comments': comments }, context_instance=RequestContext(request))
def _invoice(self, o): from django.contrib.admin.util import quote output = [] if dsettings.DEBUG: vname = 'assopy-invoice-html' else: vname = 'assopy-invoice-pdf' for i in o.invoices.all(): url = urlresolvers.reverse(vname, kwargs={ 'order_code': quote(o.code), 'code': quote(i.code), }) output.append('<a href="%s">%s%s</a>' % (url, i.code, ' *' if not i.payment_date else '')) return ' '.join(output)
def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( "admin:%s_%s_change" % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name, )
def render(self, name, value, *args, **kwargs): """Custom render method. If the form has not been injected to the widget, failover to the original widget. ``url`` refers to the ``POST`` location used by TinyMCE's AJAX save function. If we're on an add page, we don't want to POST save anything. """ if not hasattr(self, 'form'): # the form has not been injected to the widget, failover to the # original widget return mark_safe(self.widget.render(name, value, *args, **kwargs)) opts = self.form.instance._meta # url refers to the POST location used by TinyMCE's AJAX save function. # If we're on an add page, we don't want to POST save anything. url = None if self.form.instance.pk: url = reverse('admin:%s_%s_change' % ( opts.app_label, opts.model_name), args=(quote(self.form.instance.pk),)) output = [self.widget.render(name, value, *args, **kwargs)] # name - input name, value, kwargs['attrs']['id'] input id for klass, js in self.widget_overrides: if isinstance(self.widget, klass): output.append('<script type="text/javascript">') output.append(js % (kwargs['attrs'].get('id', ''), url)) output.append('</script>') break return mark_safe(''.join(output))
def render(self, name, value, *args, **kwargs): """Custom render method. If the form has not been injected to the widget, failover to the original widget. ``url`` refers to the ``POST`` location used by TinyMCE's AJAX save function. If we're on an add page, we don't want to POST save anything. """ if not hasattr(self, 'form'): # the form has not been injected to the widget, failover to the # original widget return mark_safe(self.widget.render(name, value, *args, **kwargs)) opts = self.form.instance._meta # url refers to the POST location used by TinyMCE's AJAX save function. # If we're on an add page, we don't want to POST save anything. url = None if self.form.instance.pk: url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(quote(self.form.instance.pk), )) output = [self.widget.render(name, value, *args, **kwargs)] # name - input name, value, kwargs['attrs']['id'] input id for klass, js in self.widget_overrides: if isinstance(self.widget, klass): output.append('<script type="text/javascript">') output.append(js % (kwargs['attrs'].get('id', ''), url)) output.append('</script>') break return mark_safe(''.join(output))
def format_callback(obj): is_managed_content = isinstance(obj, BaseContent) has_admin = obj.__class__ in admin_site._registry or is_managed_content opts = obj._meta if has_admin and not isinstance(obj, ObjectPermission): try: admin_url = reverse( '%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()), )) except NoReverseMatch: admin_url = '' p = '%s.%s' % (opts.app_label, opts.get_delete_permission()) if is_managed_content or hasattr(obj, 'can_delete'): if is_managed_content: obj = obj.get_real_instance() if not obj.can_delete( user ): # maybe is not a BaseContent but implements can_delete objects_without_delete_perm.add(obj) elif not bypass_django_perms and not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. if admin_url: return mark_safe(u'%s: <a href="%s">%s</a>' % (escape( capfirst(opts.verbose_name)), admin_url, escape(obj))) else: return u'%s: %s' % (capfirst( opts.verbose_name), force_unicode(obj)) else: # Don't display link to edit, because it either has no # admin or is edited inline. return u'%s: %s' % (capfirst( opts.verbose_name), force_unicode(obj))
def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.module_name), args=[quote(pk)], current_app=self.model_admin.admin_site.name)
def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote( object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [{ "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset( self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user"))] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context)
def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get( '/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(self.pk)) self.assertContains(response, escape(self.pk)) self.failUnlessEqual(response.status_code, 200)
def test_changelist_to_changeform_link(self): "The link from the changelist referring to the changeform of the object should be quoted" response = self.client.get( '/test_admin/admin/admin_views/modelwithstringprimarykey/') should_contain = """<tr class="row1"><th><a href="%s/">%s</a></th></tr>""" % ( quote(self.pk), escape(self.pk)) self.assertContains(response, should_contain)
def remove(self, obj, **kwargs): """ This will not work without a custom get_list_display like above in this class. """ request = kwargs.pop('request') if self.has_delete_permission(request, obj): info = obj._meta.app_label, obj._meta.module_name delete_url = reverse('admin:%s_%s_delete' % info, args=(quote(obj.pk), quote(self.prescription.pk))) return ( '<a href="%s" class="btn btn-mini alert-error" ' 'title="Delete"><i class="icon-trash"></i></a>') % delete_url else: return ""
def url_for_result(self, result): pk = getattr(result, self.pk_attname) continente = result.continente.id pk = '%s-%s' % (pk, continente) return reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name)
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ return mark_safe("%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))
def setUp(self): super(ActionAdminTests, self).setUp() self.prescription = self.make(Prescription) user = User.objects.create(username="******") url = reverse("admin:risk_action_changelist", args=(quote(self.prescription.id),)) self.request = self._mocked_authenticated_request(url, user) self.admin = ActionAdmin(Prescription, site) self.admin.prescription = self.prescription
def response_add(self, request, obj, *args, **kwargs): resp = super(UndeletePageAdminMixin, self).response_add(request, obj, *args, **kwargs) if resp.status_code == 302 and resp['Location'].startswith('../'): viewname = 'admin:%s_%s_change' % ( obj._meta.app_label, obj._meta.module_name) resp['Location'] = reverse(viewname, args=(quote(obj.pk),)) return resp
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ if self.content_type and self.object_id: return mark_safe(u"%s/%s/%s/" % (self.app_label, self.content_type, quote(self.object_id))) return None
def response_add(self, request, obj, *args, **kwargs): resp = super(UndeletePageAdminMixin, self).response_add(request, obj, *args, **kwargs) if resp.status_code == 302 and resp['Location'].startswith('../'): viewname = 'admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name) resp['Location'] = reverse(viewname, args=(quote(obj.pk), )) return resp
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) return reverse(url_name, args=(quote(self.object_id),)) return None
def setUp(self): super(ActionAdminTests, self).setUp() self.prescription = self.make(Prescription) user = User.objects.create(username='******') url = reverse('admin:risk_action_changelist', args=(quote(self.prescription.id),)) self.request = self._mocked_authenticated_request(url, user) self.admin = ActionAdmin(Prescription, site) self.admin.prescription = self.prescription
def test_url_conflicts_with_add(self): "A model with a primary key that ends with add should be visible" add_model = ModelWithStringPrimaryKey(id="i have something to add") add_model.save() response = self.client.get( '/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(add_model.pk)) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain)
def test_url_conflicts_with_history(self): "A model with a primary key that ends with history should be visible" history_model = ModelWithStringPrimaryKey(id="history") history_model.save() response = self.client.get( '/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(history_model.pk)) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain)
def handle_create_node(instance, node_info): pk = quote(getattr(instance, pk_attname)) node_info.update( url=self.get_admin_url('change', (quote(pk),)), move_url=self.get_admin_url('move', (quote(pk),)), label='<span class="ex-rubric %(method)s %(active)s%(is_characteristic)s%(is_mark)s%(is_relation)s%(has_system_flags)s">%(label)s <i class="fa fa-exclamation-triangle ex-has-system-flags"></i> <i class="fa fa-list ex-characteristic"></i> <i class="fa fa-tags ex-mark"></i> <i class="fa fa-link ex-relation"></i><span class="ex-label">%(method_display)s</span> <i class="fa fa-power-off"></i> %(tags)s<span class="path">%(path)s</span></span>' % { 'label': node_info['label'], 'method': instance.get_classification_method(), 'method_display': instance.get_classification_method_display(), 'active': 'on' if instance.active else 'off', 'is_characteristic': ' is-characteristic' if instance.attribute_mode == Rubric.ATTRIBUTE_IS_CHARACTERISTIC else '', 'is_mark': ' is-mark' if instance.attribute_mode == Rubric.ATTRIBUTE_IS_MARK else '', 'is_relation': ' is-relation' if instance.attribute_mode == Rubric.ATTRIBUTE_IS_RELATION else '', 'has_system_flags': ' has-system-flags' if instance.system_flags else '', 'path': instance.path, 'tags': ''.join(['<span class="ex-label tag">%s</span>' % tag for tag in instance.tags.split()]) if instance.tags else '' } )
def url_for_result(self, result): if self.model_admin.changelist_link_detail: pk = getattr(result, self.pk_attname) return reverse('admin:%s_%s_detail' % (self.opts.app_label, self.opts.module_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name) else: return super(DetailChangeList, self).url_for_result(result)
def get_history_url(obj, history_index=None, site="admin"): try: app, model = obj._meta.app_label, obj._meta.module_name except AttributeError: app, model = obj._meta.app_label, obj._meta.model_name if history_index is not None: history = obj.history.order_by('history_id')[history_index] return reverse( "{site}:{app}_{model}_simple_history".format(site=site, app=app, model=model), args=[quote(obj.pk), quote(history.history_id)], ) else: return reverse("{site}:{app}_{model}_history".format(site=site, app=app, model=model), args=[quote(obj.pk)])
def url_for_result(self, result): if self.model_admin.changelist_link_detail: pk = getattr(result, self.pk_attname) return reverse('admin:%s_%s_detail' % (self.opts.app_label, self.opts.module_name), args=(quote(pk), ), current_app=self.model_admin.admin_site.name) else: return super(DetailChangeList, self).url_for_result(result)
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ if self.content_type and self.object_id: url_name = 'admin:%s_%s_change' % (self.content_type.app_label, self.content_type.model) return reverse(url_name, args=(quote(self.object_id), )) return None
def balloons_regenerate_delivery_key_view(request): contest = get_object_or_404(Contest, id=request.contest.id) access_data = BalloonsDeliveryAccessData.objects \ .get_or_create(contest=contest)[0] access_data.valid_until = None access_data.generate_key() access_data.save() return redirect('oioioiadmin:contests_contest_change', quote(request.contest.id))
def f(self, obj): link_cond = '%s=%s' % (field.related_query_name(), quote(obj.pk)) link_text = u'%s (%s)' % (field.name.title(), getattr(obj, '%s__count' % field.name)) try: url = reverse('admin:%s_%s_changelist' % (related_model._meta.app_label, related_model._meta.module_name)) except NoReverseMatch: return link_text return u'<a href="%s?%s">%s</a>' % (url, link_cond, link_text)
def url_for_result(self, result): if self.url_status == -1: return super(PartsRecycleChangeList, self).url_for_result(result) else: pk = getattr(result, self.pk_attname) url_suffix = statusUrl.get_url_suffix_by_status(self.url_status) url = reverse('admin:%s_%s_change_%s' % (self.opts.app_label, self.opts.model_name, url_suffix), args=(quote(pk), ), current_app=self.model_admin.admin_site.name) return url
def _invoice(self, o): from django.contrib.admin.util import quote output = [] if dsettings.DEBUG: vname = 'assopy-invoice-html' else: vname = 'assopy-invoice-pdf' for i in o.invoices.all(): url = urlresolvers.reverse( vname, kwargs={ 'order_code': quote(o.code), 'code': quote(i.code), } ) output.append( '<a href="%s">%s%s</a>' % ( url, i.code, ' *' if not i.payment_date else '') ) return ' '.join(output)
def f(obj): link_cond = '%s=%s' % (target_field_name, quote(obj.pk)) link_text = u'%s (%s)' % (target_model._meta.verbose_name_plural.title(), getattr(obj, '%s__count' % source_field_name)) try: url = reverse('admin:%s_%s_changelist' % (target_model._meta.app_label, target_model._meta.module_name)) except NoReverseMatch: return link_text return u'<a href="%s?%s">%s</a>' % (url, link_cond, link_text)
def show_treatments(context, location): current = context['current'] treatments = Treatment.objects.filter( register__prescription=current, location__name=location) url = reverse('admin:risk_treatment_complete', args=(quote(current.pk),)) return { 'current': current, 'treatments': treatments, 'url': url }
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ 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 format_callback(obj): opts = obj._meta admin_url = reverse('%s:%s_%s_change' % (modeladmin.admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) # Display a link to the admin page. return mark_safe(u'%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj)))
def get_admin_url(self): if self.content_type and self.object_id: model = self.content_type.model_class() if hasattr(model, 'get_admin_url'): return model.get_admin_url( content_type=self.content_type, object_id=self.object_id) return ( "{0}/{1}/{2}/" .format( self.content_type.app_label, self.content_type.model, quote(self.object_id))) return None
def all_treatments(self, obj): if obj.treatment_set.count() > 0: output = '<ul>' for treatment in obj.treatment_set.all(): if treatment.complete: status_class = ' class="text-success"' status_icon = '<i class="icon-ok"></i> ' else: status_class = '' status_icon = '' treatment_url = reverse('admin:risk_treatment_change', args=(quote(treatment.pk), quote(self.prescription.pk))) output += '<li%s><a href="%s">%s%s (%s)</a></li>' % ( status_class, treatment_url, status_icon, treatment.description, treatment.location) output += '</ul>' else: if obj.alarp: output = 'No treatments required' else: output = 'No treatments' if not obj.alarp and self.prescription.is_draft: url = reverse('admin:risk_treatment_add', args=(quote(self.prescription.pk),), current_app=self.admin_site.name) url += '?register=%d' % obj.pk output += ( '<br><a id="add_treatment_%(pk)s" ' 'onclick="return showAddAnotherPopup(this);" ' 'class="add-another" href="%(url)s">' '<i class="icon-plus"></i> Add a treatment</a>' ) % { 'pk': obj.pk, 'url': url, } return output
def f(obj): link_args = getattr(obj, field.attname) if link_args is None: return u'(None)' # we could use field.name to output __unicode__() of the related object, # but that would require to prefetch related objects, which can be slow link_text = u'%s %s' % (related_model.__name__, getattr(obj, field.attname)) try: url = reverse('admin:%s_%s_change' % (related_model._meta.app_label, related_model._meta.module_name), args=[quote(link_args)]) except NoReverseMatch: return link_text return u'<a href="%s">%s</a>' % (url, link_text)
def format_link_callback(obj, admin_site): 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, opts.get_delete_permission()) # Display a link to the admin page. return mark_safe( u'%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 u'%s: %s' % (capfirst(opts.verbose_name), force_unicode(obj))
def generate_url(self, instance, default=False): """ devuelve la url con la publicacion de datos para una determinada instancia :param instance: es la instancia de la que se desea obtener la url :return: devuelve la url de la instancia """ if default or not hasattr(instance, 'easydata_generate_url'): if self.entidad is None: return "" else: return reverse('easydata.views.publish.publish_model', args=[ self.aplicacion, self.entidad.nombre, self.nombre, quote(instance.pk), 'xml' ]) else: return getattr(instance, 'easydata_generate_url')()
def history_view(self, request, object_id, extra_context=None): if not self.has_change_permission(request): raise PermissionDenied object_id = unquote( object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [{ "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset( self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user"))] # Compile the context. full_action_list = [] for log_action in LogEntry.objects.filter( object_id=object_id, content_type__id__exact=ContentType.objects.get_for_model( self.model).id).select_related().order_by('action_time'): while (len(action_list) and (log_action.action_time > action_list[0]['revision'].date_created)): full_action_list.append(action_list.pop(0)) full_action_list.append({"log": log_action}) #print len(action_list) while (len(action_list)): full_action_list.append(action_list.pop(0)) context = {"action_list": full_action_list} context.update(extra_context or {}) return super(reversion.VersionAdmin, self).history_view(request, object_id, context) return super(ModeratedAdmin, self).history_view(request, object_id, context)
def _get_action_list(self, request, object_id, extra_context=None): """Renders the history view.""" object_id = unquote( object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [{ "version": version, "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.module_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset( self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user"))] return action_list
def admin_urlquote(value): return quote(value)
def show_treatments(context, location): current = context['current'] treatments = Treatment.objects.filter(register__prescription=current, location__name=location) url = reverse('admin:risk_treatment_complete', args=(quote(current.pk), )) return {'current': current, 'treatments': treatments, 'url': url}
def url_for_result(self, result): return "%s/" % quote(getattr(result, self.pk_attname))