Code-Apprentice
Code-Apprentice

Reputation: 83557

Add menu items to Django admin site

I want to do something similar to How to add report section to the Django admin? which explains how to register custom endpoints for the admin site. If I register a URL in this way, how do I add a link to that view? The only way I've found so far is something like this:

class CustomAdmin(admin.ModelAdmin):
    def changelist_view(self, request, extra_context=None):
        return render(request, 'my_page.html')


class ProxyModel(models.MyModel):
    class Meta:
        verbose_name = 'Report'
        verbose_name_plural = 'Report'
        proxy = True

admin.site.register(ProxyModel, CustomAdmin)

This seems like a code smell for at least two reasons:

  1. I'm overriding changelist_view() to render my own report template which isn't a "change list".

  2. It requires a proxy model even if the report doesn't rely on a model or relies on multiple models.

Is there a better way to do this?

Upvotes: 4

Views: 7595

Answers (1)

Raydel Miranda
Raydel Miranda

Reputation: 14360

Override the base admin template in order to add a section for your custom menu, then you should be able to use the {% url ... %} tag there in order to point to your view/s.

See: Overriding admin templates

You even could have a model for those menu items lets called AdminMenuItems.

class AdminMenuItems(models.Model):
    title = models.CharField(max_length=255)
    # The name of your url according your urls conf.
    url_name = models.CharField(max_length=255)

Then in your custom admin template, it could be something like:

<ul>
{% for item in menu_intems %}
    <li><a href="{% url item.url_name %}">item.title</a></li>
{% endfor %}
</ul>

And you can add those items to the context via a context processor.

Upvotes: 3

Related Questions