是否可以在django-admin中对某个模型的列表展示页面进行模型描述或者描述?
我说的是当你点击 django-admin 主页上的模型名称链接时,当你转到该模型的列表显示页面时。表格顶部将写有说明。有点像
“此模型用于记录我们的抓取将获取的所有帐户......等等”
这样的事情,有可能吗?
最佳答案
如果添加到 Django 管理的核心中,那将是一个非常好的功能。在此之前,这里是对您的问题的快速演练。
假设您要打印每个模型的 docstring
,如下所示:
class MyModel(models.Model):
"""
I wanna get printed in the Admin!
"""
# model fields here
因此,您想在 change_list
中打印它页。好。
创建 custom template tag (在您的应用内或创建另一个将包含全局模板标签/过滤器的应用)像这样:
from django import template from django.utils.html import mark_safe register = template.Library() @register.simple_tag() def model_desc(obj): if obj.__doc__: return mark_safe('<p>{}</p>'.format(obj.__doc__)) return ''
现在,在您的项目目录(
manage.py
所在的位置)中创建如下结构:project/ project/ project stuff here, i.e wsgi.py, settings etc myapp/ myapp stuff here, i.e models, views etc templates/ admin/ change_list.html manage.py
在
change_list.html
中添加以下内容:{% extends 'admin/change_list.html' %} {% load yourapp_tags %} {# block.super will print the "Select <Model> to change" h1 title #} {# The model_desc template tag is the one you created and prints the docstring of the given model #} {% block content_title %}{{ block.super }}<br>{% model_desc cl.model %}{% endblock %}
截图如下:
[更新]:我有 seen in the source当没有指定 docstring
时,Django 会以如下形式为您生成一个:ModelName(model_field_name1, model_field_name2, ...)
。如果您不想这样,只需执行以下操作:
class MyModelWithoutDocstring(models.Model):
# model fields here
MyModelWithoutDocstring.__doc__ = '' # "reset" the __doc__ on this model.
关于python - django-admin 中的模型描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42826287/