Getting Django admin url for an object

前端 未结 9 1569
有刺的猬
有刺的猬 2020-12-02 03:51

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:

相关标签:
9条回答
  • 2020-12-02 04:28
    from django.core.urlresolvers import reverse
    def url_to_edit_object(obj):
      url = reverse('admin:%s_%s_change' % (obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )
      return u'<a href="%s">Edit %s</a>' % (url,  obj.__unicode__())
    

    This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.

    0 讨论(0)
  • 2020-12-02 04:31

    If you are using 1.0, try making a custom templatetag that looks like this:

    def adminpageurl(object, link=None):
        if link is None:
            link = object
        return "<a href=\"/admin/%s/%s/%d\">%s</a>" % (
            instance._meta.app_label,
            instance._meta.module_name,
            instance.id,
            link,
        )
    

    then just use {% adminpageurl my_object %} in your template (don't forget to load the templatetag first)

    0 讨论(0)
  • 2020-12-02 04:36

    There's another way for the later versions, for example in 1.10:

    {% load admin_urls %}
    <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
    <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
    

    Where opts is something like mymodelinstance._meta or MyModelClass._meta

    One gotcha is you can't access underscore attributes directly in Django templates (like {{ myinstance._meta }}) so you have to pass the opts object in from the view as template context.

    0 讨论(0)
提交回复
热议问题