2017-03-16 80 views
0

是否可以在django-admin的某个模型的列表显示页面上放置模型描述或描述?在django-admin中的模型描述

我在说的是,当你点击django-admin主页上的模型名称链接,以及当你转到该模型的列表显示页面时。表格上方会有描述。像

东西“这种模式是用于记录将通过我们的刮中获取所有帐户....等等”

类似的东西,这可能吗?

+0

以下答案是否适用于你的情况? –

+0

是的,我在HTML方面做了一些改变。只需将templatetag放在不同的行中,以确保右侧的按钮对齐不会受到影响。谢谢! –

回答

4

这将是一个非常好的功能被添加到Django的管理员核心。在此之前,您可以快速浏览您的问题。

让我们假设你要打印的每个模型的docstring,就像这样:

class MyModel(models.Model): 
    """ 
    I wanna get printed in the Admin! 
    """ 

    # model fields here 

所以,你想打印在change_list页。好。

  1. 创建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 '' 
    
  2. 现在,您的项目目录中(其中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 
    
  3. 里面的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 %} 
    

以下是截图:

Model docstring in Django admin

[更新]:我有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. 
+0

在第2步中,您要求用户创建全局change_list.html。但是每个模型都会有自己的change_list.html。你可能想纠正这一点。 –

+0

这取决于你想要如何模块化。我决定为所有模型全局添加它,以在'change_list'页面中显示它们的'docstring'。 –