Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin Pass A Variable to base_site.html

I am using django-livesettings to save the site title to the database. To be able to access a config value, however, you need to pass the variable to the template via a view:

http://django-livesettings.readthedocs.org/en/latest/usage.html#accessing-your-value-in-a-view

What method of the admin.ModelAdmin class can I override to pass variables to the base_site.html, where the admin site title "Django Site Admin" is located?

This answer may come close but I don't know what it misses: Django how to pass custom variables to context to use in custom admin template?

like image 426
yretuta Avatar asked Dec 11 '25 20:12

yretuta


1 Answers

The most elegant solution I found is here: https://stackoverflow.com/a/36421610/7521854

Essentially, it overrides your admin site's each_context method to add as many custom variables as required. The updated context is applied to all admin pages without any further effort.

In my case, I want to have a custom footer displaying release version info. This info is taken from a file which is automatically updated with a git describe command during deployment.

File: 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')

And the related footer tag is:

{% block footer %}
<div class="copyright-center">
    <p><small>My Admin {{releaseTag}} Copyright &copy; MyCo</small></p>
</div>
{% endblock %}
like image 81
Agoun Avatar answered Dec 14 '25 10:12

Agoun