pythondjangodjango-admincustomization

Add custom button to django admin panel


I want to add button to admin panel to my model, I have overwrite template (path: templetes/admin/myapp/mymodel/change_list.html)

change_list.html

{% extends "admin/change_list.html" %}
{% load i18n admin_static %}

{% block result_list %}
<div class="object-tools">
    <a href="{% url 'myurl' %}" class="btn btn-high btn-success">Import</a>
</div>
{{ block.super }}
{% endblock %}

In admin.py

class ImportAdmin(admin.ModelAdmin):
    change_list_template = 'admin/myapp/mymodel/change_list.html'

But I can not see the button.


Solution

  • It works as below ("Import" button right side).

    enter image description here

    Django = 1.11

    admin/change_list.html: Add the URL with "admin:". Otherwise, it will not resolve the URL.

    {% extends "admin/change_list.html" %}
    {% load i18n admin_static %}
    
    {% block object-tools-items %}
    {{ block.super }}
    <li>
        <a href="{% url 'admin:myurl' %}" class="btn btn-high btn-success">Import</a>
    </li>
    {% endblock %}
    

    admin.py: Add the custom template URL

    class ImportAdmin(admin.ModelAdmin):
        change_list_template = 'admin/myapp/mymodel/change_list.html'
    

    Django >1.8

    settings.py: TEMPLATE_LOADERS deprecated. Set TEMPLATES as below.

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': False,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'loaders': [
                    'admin_tools.template_loaders.Loader',
                    ('django.template.loaders.cached.Loader', [
                        'django.template.loaders.filesystem.Loader',
                        'django.template.loaders.app_directories.Loader',
                    ]),
                ],
    
            },
        },
    ]