Getting Django admin url for an object
Before Django 1.0 there was an easy way to get the admin url of an object, and I had written a small filter that I'd use like this: <a href="{{ object|admin_url }}" .... > ... </a>
Basically I was using the url reverse function with the view name being 'django.contrib.admin.views.main.change_stage'
reverse( 'django.contrib.admin.views.main.change_stage', args=[app_label, model_name, object_id] )
to get the url.
As you might have guessed, I'm trying to update to the latest version of Django, and this is one of the obstacles I came across, that method for getting the admin url doesn't work anymore.
How can I do this in django 1.0? (or 1.1 for that matter, as I'm trying to update to the latest version in the svn).
I had a similar issue where I would try to call reverse('admin_index')
and was constantly getting django.core.urlresolvers.NoReverseMatch
errors.
Turns out I had the old format admin urls in my urls.py file.
I had this in my urlpatterns:
(r'^admin/(.*)', admin.site.root),
which gets the admin screens working but is the deprecated way of doing it. I needed to change it to this:
(r'^admin/', include(admin.site.urls) ),
Once I did that, all the goodness that was promised in the Reversing Admin URLs docs started working.
You can use the URL resolver directly in a template, there's no need to write your own filter. Eg
{% url 'admin:index' %}
{% url 'admin:polls_choice_add' %}
{% url 'admin:polls_choice_change' choice.id %}
{% url 'admin:polls_choice_changelist' %}
Ref: Documentation
from django.core.urlresolvers import reverse
def url_to_edit_object(object):
url = reverse('admin:%s_%s_change' % (object._meta.app_label, object._meta.model_name), args=[object.id] )
return u'<a href="%s">Edit %s</a>' % (url, object.__unicode__())
这与hansen_j的解决方案类似,只不过它使用了url命名空间admin:作为管理员的默认应用程序名称空间。
链接地址: http://www.djcxy.com/p/62006.html上一篇: Django修复Admin复数
下一篇: 获取对象的Django管理url