Django - 如何从模型实例中获取管理员 URL

2023-11-08Python开发问题
4

本文介绍了Django - 如何从模型实例中获取管理员 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试在保存新模型实例时向用户发送电子邮件,并且我希望电子邮件包含指向该模型实例管理页面的链接.有没有办法获得正确的网址?我认为 Django 必须将这些信息存储在某个地方.

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 the correct URL? I figure Django must have that information stored somewhere.

推荐答案

这个 Django 片段 应该做:

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,))

self 引用父模型类,即self.id 引用对象的实例id.您也可以将其设置为 property通过将 @property 装饰器粘贴在方法签名之上来建模.

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.

Chris Pratt 下面 的答案在 ContentType 表.我的回答仍然有效",并且较少依赖于 Django 模型 instance._meta 内部.仅供参考.

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.

这篇关于Django - 如何从模型实例中获取管理员 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11