django-admin中的模型描述 [英] Model description in django-admin
问题描述
是否可以在django-admin中的某个模型的列表显示页面上放置一个模型描述或描述?
我正在谈论诸如when您单击django-admin主页上的模型名称链接,然后单击该模型的列表显示页面。表格顶部将写有说明。像这样的
此模型用于记录所有将由我们的抓取工具获取的帐户...。依此类推
类似的事情,有可能吗?
这将是一个非常不错的功能Django管理员的核心。在此之前,这里将快速解答您的问题。
让我们假设您要打印每个模型的 docstring
,像这样:
class MyModel(models.Model):
我想要
#此处的模型字段
因此,您希望将其打印在
[更新] :我有在源代码中看到,当未指定 docstring
时,Django将为您生成以下格式的文件: ModelName(model_field_name1,model_field_name2,...)
。如果您不希望这样做,只需执行以下操作:
class MyModelWithoutDocstring(models.Model):
#此处的模型字段
MyModelWitho utDocstring .__ doc__ =’#在此模型上重置 __doc__。
Is it possible to put a model description or description on the list display page of a certain model in django-admin?
I'm talking about something like when you click a model name link on the homepage of django-admin and when you go to the list display page of that model. There will be a description written on top of the table. Something like
"This model is used to log all accounts that will be fetched by our scrape.... And so on"
Something like that, is it possible?
That would be a very nice feature to be added in the core of Django's admin. Until then here's a quick walkthrough to your question.
Let's assume that you want to print the docstring
of each model, like this:
class MyModel(models.Model):
"""
I wanna get printed in the Admin!
"""
# model fields here
So, you want to print it in the change_list
page. Good.
Create a custom template tag (either within your app or create another app that will hold the global template tags/filters) like this:
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 ''
Now, inside your project directory (where
manage.py
lives) create a structure like this: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
Inside the
change_list.html
add these:{% 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 %}
Here's a screenshot:
[UPDATE]: I have seen in the source that when there is no docstring
specified, Django will generate one for you in the following form: ModelName(model_field_name1, model_field_name2, ...)
. If you do not want that, simply do this:
class MyModelWithoutDocstring(models.Model):
# model fields here
MyModelWithoutDocstring.__doc__ = '' # "reset" the __doc__ on this model.
这篇关于django-admin中的模型描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!