Django - How to get admin url from model instance

前端 未结 5 420
情书的邮戳
情书的邮戳 2021-02-01 15:34

I\'m trying to send an email to a user when a new model instance is saved and I want the email to include a link to the admin page for that model instance. Is there a way to get

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 16:35

    This Django snippet should do:

    from django.urls import reverse
    from django.contrib.contenttypes.models import ContentType
    from django.db import models
    
    class MyModel(models.Model):
    
        def get_admin_url(self):
            content_type = ContentType.objects.get_for_model(self.__class__)
            return reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(self.id,))
    

    The self refers to the parent model class, i.e. self.id refers to the object's instance id. You can also set it as a property on the model by sticking the @property decorator on top of the method signature.

    EDIT: The answer by Chris Pratt below saves a DB query over the ContentType table. My answer still "works", and is less dependent on the Django model instance._meta internals. FYI.

提交回复
热议问题