将模型范围的帮助文本添加到django模型的管理表单中 [英] Adding model-wide help text to a django model's admin form
问题描述
在我的django应用程序中,我可以添加自定义的帮助文本到我的一些模型的管理员更改表单。注意我不是在个别字段中设置的字段具体 help_text
属性。例如,在 My_App
中的 My_Model
的更改表单的顶部我想添加一些表示有关我的模型的其他信息,请参阅 http://example.com 的HTML,以提供链接一个内部文档维基。
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 %}
我已选择将此template / 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/
这篇关于将模型范围的帮助文本添加到django模型的管理表单中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!