Pietro
Pietro

Reputation: 1835

Add custom page to django admin without a model

I'm trying to add a custom page to the admin without a model association.

This is what I achieved so far.

class MyCustomAdmin(AdminSite):

    def get_urls(self):
        from django.conf.urls import url

        urls = super(MyCustomAdmin, self).get_urls()
        urls += [
            url(r'^my_custom_view/$', self.admin_view(MyCustomView.as_view()))
        ]
        return urls

class MyCustomView(View):
    template_name = 'admin/myapp/views/my_custom_template.html'

    def get(self, request):
        return render(request, self.template_name, {})

    def post(self, request):
      # Do something
      pass

admin_site = MyCustomAdmin()

admin_site.register(MyModel1)
admin_site.register(MyModel2)
# etc...

This is actually working but the problem is that with this solution I loose some apps from the Django admin interface (account, auth, socialaccounts, sites).

Upvotes: 9

Views: 9752

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

This is because your other admins are using the default admin.site. You need to totally replace the default admin.site with your own as explained here (you may also want to read this too).

Or you can just do it piggy-style by monkeypatching the default admin.site.get_urls() method:

from django.contrib import admin

_admin_site_get_urls = admin.site.get_urls

def get_urls():        
    from django.conf.urls import url
    urls = _admin_site_get_urls()
    urls += [
            url(r'^my_custom_view/$',
                 admin.site.admin_view(MyCustomView.as_view()))
        ]
    return urls

admin.site.get_urls = get_urls

Legal disclaimer : I won't be held responsible for any kind of any unwanted side-effect of this "solution", including (but not restricted too) your coworkers defenestrating you on the next code review. It's a dirty solution. It's a mess. It stinks. It's evil. You shouldn't do that, really.

Upvotes: 4

Related Questions