python - Django:allow_tags和short_description如何工作?

标签 python django django-models django-admin

models.py 中执行此操作的基本方法,示例:

class Foo(models.Model):
    title = models.CharField(max_length=200)
    ...

    def custom_tag(self):
        return ('custom: %s' % self.title)
    custom_tag.allow_tags = True
    custom_tag.short_description = _("Custom Tag")

或者,如果在 admin.py 文件内;

class FooAdmin(admin.ModelAdmin):
    list_display = ['title', 'custom_tag', ...]
    ...

    def custom_tag(self, instance):
        return ('custom: %s' % instance.title)
    custom_tag.allow_tags = True
    custom_tag.short_description = _("Custom Tag")


admin.site.register(Foo, FooAdmin)

我的问题是,allow_tagsshort_description 是如何工作的?在哪里可以找到相关文档?

我在 documentation 找不到它或者也可以访问 source code

最佳答案

您正在查看文档的开发版本。如果你看一下 Django 1.10 的那个(向下滚动到“自版本 1.9 起已弃用”)您会看到他们正在删除 allow_tags 选项,并将其替换为实现相同目的的其他方法。有很多关于如何使用 short_description 的示例,因为它尚未被弃用。

如果你真的想看源代码,here's the line where it gets the short description 。不必担心 allow_tags,因为它已在 1.11 中删除 - 现在应该通过使用 mark_safe() 将字符串标记为安全来自动完成。

<小时/>

顺便说一句,您不需要在这两个地方添加 custom_tag() 方法。管理员会在模型和管理类中查找它,因此一个就足够了。如果不打算在管理之外使用它,我建议将其放置在管理类中,并避免使模型变得更加复杂。

关于python - Django:allow_tags和short_description如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316686/

相关文章:

Python gmplot 'centerLat' 未定义

python - 将字符串转换为多个 float

python - 如何通过人脸检测得到准确的人数?

python - 处理 Django 模型和关系数据的正确/最有效的方法

Django Rest Framework - 使用相同实例的序列化器内的序列化器

django - Django ORM 中 ImageField 的默认图像

python - 有没有办法使用 Django 为 SQL 表概念指定列的创建顺序?

python - Visual Studio Code新功能连接到Jupyter Notebook,是否也可以连接到JupyterHub?

python - 如何让 django model utils Choices 处理小写和大写

django Manytomany 通过