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

发布于 2024-09-19 04:37:05 字数 360 浏览 4 评论 0原文

在我的 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

时间你老了 2024-09-26 04:37:06

使用管理员的 字段集

class MyAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('first', 'second', 'etc'),
            'description': "This is a set of fields group into a fieldset."
        }),
    )
    # Other admin settings go here...

您可以在管理员中拥有多个字段集。每个都可以有自己的标题(将上面的 None 替换为标题)。您还可以将 'classes': ('collapse',), 添加到字段集,使其开始折叠(wide 类使数据字段更宽,而其他类名意味着 CSS 所说的任何内容)。

请注意:description 字符串被认为是安全,因此不要在其中放置任何未清理的数据。这样做是为了您可以根据需要在其中放置标记(例如您的链接),但是,块格式(例如

    列表)可能看起来错误。

Use the admin's fieldsets:

class MyAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('first', 'second', 'etc'),
            'description': "This is a set of fields group into a fieldset."
        }),
    )
    # Other admin settings go here...

You can have multiple fieldsets in an admin. Each can have its own title (replace the None above with the title). You can also add 'classes': ('collapse',), to a fieldset to have it start out collapsed (the wide class makes the data fields wider, and other class names mean whatever your CSS says they do).

Be careful: the description string is considered safe, so don't put any uncleaned data in there. This is done so you can put markup in there as needed (like your link), however, block formatting (like <ul> lists) will probably look wrong.

南风起 2024-09-26 04:37:06

有一种相当简单但记录不足的方法可以实现这一点。

在 Admin 类中定义 render_change_form

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

# 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().render_change_form(request, context, *args, **kwargs)

创建自定义模板

接下来,您需要创建该自定义模板 (change_form_help_text.html) 并扩展默认的“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/ 中,但这也很灵活。


更多信息请访问:

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

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

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

Define render_change_form in the Admin class

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().render_change_form(request, context, *args, **kwargs)

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 %}

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


More info available at:

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

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

潜移默化 2024-09-26 04:37:06

如果我明白你想要什么,下面的代码应该可以满足你的要求。

def __init__(self, *args, **kwargs):
        super(ClassName, self).__init__(*args, **kwargs)
        if siteA:
            help_text = "foo"
        else:
            help_text = "bar"
        self.form.fields["field_name"].help_text = help_text

这是使用某些逻辑来修改覆盖表单的示例。因此,您只需将其放入您覆盖的 ModelAdmin 构造函数中即可。

If I understand what you want the code below should do what you want.

def __init__(self, *args, **kwargs):
        super(ClassName, self).__init__(*args, **kwargs)
        if siteA:
            help_text = "foo"
        else:
            help_text = "bar"
        self.form.fields["field_name"].help_text = help_text

That's an example of using some logic to modify an overriden form. So you just put this in your ModelAdmin constructor that you overrode.

述情 2024-09-26 04:37:06

就像这个问题的更新一样。您可以使用 help_text

。 help_text" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.help_text

Just as an update to this question. You can do this in the model using help_text

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.help_text

述情 2024-09-26 04:37:06

从 django 3.0 开始,现在可以更轻松地覆盖管理字段的 help_text

from django.utils.translation import gettext_lazy as _

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#overriding-the-default-fields

Since django 3.0 it's now possible to override the help_text of admin fields more easily:

from django.utils.translation import gettext_lazy as _

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#overriding-the-default-fields

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文