9

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).

Pietro
  • 1,815
  • 2
  • 29
  • 63
  • Instead of replacing the `AdminSite`, try creating a custom `ModelAdmin`, for which you can define custom views: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls – interDist Sep 25 '18 at 10:47

1 Answers1

4

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.

Community
  • 1
  • 1
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118