且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将模型范围的帮助文本添加到django模型的管理表单中

更新时间:2023-12-01 21:44:52

有一个相当简单但没有证明的方式完成这个。

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/

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