New URL on django admin independent of the apps

Sandip Agarwal picture Sandip Agarwal · Jul 2, 2012 · Viewed 9.6k times · Source

I am using django 1.4 and Python 2.7.

I just have a simple requirement where I have to add a new URL to the django admin app. I know how to add URLs which are for the custom apps but am unable figure out how to add URLs which are of the admin app. Please guide me through this.

Basically the full URL should be something like admin/my_url.

UPDATE

I want a way after which I can as well reverse map the URL using admin.

Answer

Danny W. Adair picture Danny W. Adair · Jul 2, 2012

+1 for Jingo's answer to your original question. With your clarifying comment to the answer in mind: Such a URL is not "independent of the apps", it is a URL for the app "admin".

Adding a URL to the admin site is similar to ModelAdmin, by overriding get_urls(): https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-views-to-admin-sites

EDIT:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite

is an admin site, by default "the" admin site is instantiated as "django.contrib.admin.site" (and then e.g. your ModelAdmin's are registered against that). So you can subclass AdminSite for your own MyAdminSite and re-define get_urls() there:

from django.contrib.admin import AdminSite

class MyAdminSite(AdminSite):
    def get_urls():
        ...


...
my_admin_site = MyAdminSite()
...
my_admin_site.register(MyModel, MyModelAdmin)

Make sure you use my_admin_site in urls.py instead now: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf

Regarding the actual contents of get_urls(),see https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls (of course calling super() of MyAdminSite). Also note the convenient "admin_view" wrapper mentioned there.

P.S.: In theory, you could also just define get_urls() and then monkeypatch the default admin site so that it uses your get_urls() but I don't know if that would actually work - you'd probably have to monkeypatch right after its "first" import...