Adding model-wide help text to a django model's admin form

前端 未结 6 2021
抹茶落季
抹茶落季 2020-12-22 23:02

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 h

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 23:21

    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(CustomAdmin, self).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 %}

    {{ help_text }}

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

提交回复
热议问题