Getting Django admin url for an object

前端 未结 9 1716
有刺的猬
有刺的猬 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:25

    Here's another option, using models:

    Create a base model (or just add the admin_link method to a particular model)

    class CommonModel(models.Model):
        def admin_link(self):
            if self.pk:
                return mark_safe(u'%s' % (self._meta.app_label,
                        self._meta.object_name.lower(), self.pk, self))
            else:
                return mark_safe(u'')
        class Meta:
            abstract = True
    

    Inherit from that base model

       class User(CommonModel):
            username = models.CharField(max_length=765)
            password = models.CharField(max_length=192)
    

    Use it in a template

    {{ user.admin_link }}
    

    Or view

    user.admin_link()
    

提交回复
热议问题