我发现的最优雅的解决方案在这里:
https ://stackoverflow.com/a/36421610/7521854
本质上,它会覆盖您的管理站点的each_context
方法,以根据需要添加任意数量的自定义变量。更新后的上下文无需任何进一步的努力即可应用于所有管理页面。
就我而言,我希望有一个自定义页脚显示发布版本信息。此信息取自git describe
在部署期间使用命令自动更新的文件。
文件app-name/sites.py
::
class MyAdminSite(AdminSite):
""" Extends the default Admin site. """
site_title = gettext_lazy('My Admin')
site_header = gettext_lazy('My header')
index_title = gettext_lazy('My Administration')
def each_context(self, request):
version_info = ""
try:
version_info = os.environ['RELEASE_TAG']
except KeyError:
f = open(os.path.join(settings.BASE_DIR, 'assets/version.txt'), 'r')
version_info = f.read()
f.close()
os.environ['RELEASE_TAG'] = version_info
context = super(MyAdminSite, self).each_context(request)
context['releaseTag'] = version_info
return context
admin_site = MyAdminSite(name='my_custom_admin')
相关的页脚标签是:
{% block footer %}
<div class="copyright-center">
<p><small>My Admin {{releaseTag}} Copyright © MyCo</small></p>
</div>
{% endblock %}