将模型范围的帮助文本添加到 django 模型的管理表单 [英] Adding model-wide help text to a django model's admin form

查看:29
本文介绍了将模型范围的帮助文本添加到 django 模型的管理表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 django 应用程序中,我希望能够将自定义帮助文本添加到我的某些模型的管理更改表单中.注意我不是在谈论我可以在单个字段上设置的特定于字段的 help_text 属性.例如,在 My_AppMy_Model 的更改表单的顶部,我希望能够添加一些 HTML 说明有关我的模型的其他信息,请参阅http://example.com" 以提供指向内部文档 wiki 的链接.

In my django app, I would like to be able to add customized help text to the admin change form for some of my models. Note I'm not talking about the field specific help_text attribute that I can set on individual fields. For example, at the top of the change form for My_Model in My_App I'd like to be able to add some HTML that says "For additional information about My Model, see http://example.com" in order to provide a link to an internal documentation wiki.

是否有任何简单的方法可以完成此操作,或者我是否需要为模型创建自定义管理表单?如果是这样,你能举个例子说明我会怎么做吗?

Is there any simple way of accomplishing this, or do I need to create a custom admin form for the model? If so, can you give me an example of how I would do that?

推荐答案

有一种相当简单但文档不足的方法来实现这一点.

There is a fairly simple, yet underdocumented way of accomplishing this.

首先,您需要将额外的上下文传递给您的管理员.为此,您可以在管理类中定义一个 render_change_form 函数,例如:

First, you need to pass extra context to your admin. To do this, you can define a render_change_form function within your admin Class, e.g.:

# admin.py
class CustomAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
        # here we define a custom template
        self.change_form_template = 'admin/myapp/change_form_help_text.html'
        extra = {
            'help_text': "This is a help message. Good luck filling out the form."
        }

        context.update(extra)
        return super(CustomAdmin, self).render_change_form(request,
            context, *args, **kwargs)

创建自定义模板

接下来,您需要创建该自定义模板 (change_form_help_text.html) 并扩展默认的admin/change_form.html".

Creating a custom template

Next, you need to create that custom template (change_form_help_text.html) and extend the default 'admin/change_form.html'.

# change_form_help_text.html
{% extends 'admin/change_form.html' %}
{% block form_top %} 
{% if help_text %}<p>{{ help_text }}</p>{% endif %}
{% endblock %}

我已选择将此模板放在 templates/admin/myapp/中,但这也很灵活.

I've chosen to place this template inside templates/admin/myapp/, but this is also flexible.

更多信息,请访问:

http://davidmburke.com/2010/05/24/django-hack-adding-extra-data-to-admin-interface/

http://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowcanIpassextracontextvariablesintomyaddandchangeviews

这篇关于将模型范围的帮助文本添加到 django 模型的管理表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆