django admin, extending admin with custom views

前端 未结 4 1427
花落未央
花落未央 2021-02-07 13:06

I would like to request some assistance regarding this matter.

I have followed this guide to add a view to my admin.

I am using the same code that the site has a

4条回答
  •  青春惊慌失措
    2021-02-07 13:42

    The guide you linked is old and I was surprised to not find anything directly answering your question in the last year or so.

    1. Create a new Admin Site in your app's admin.py or in a convenient place.
    2. Create a function in the new AdminSite that augments the get_urls() function with your extra urls.
    3. Make sure your project urls.py links to the newly created AdminSite.

    The below works with Python 3.5.1 and Django 1.9.6.


    my_app/admin.py

    from django.contrib import admin
    from django.contrib.admin import AdminSite
    from django.http import HttpResponse
    
    from my_app.models import SomeModel
    
    
    class MyAdminSite(AdminSite):
    
        def custom_view(self, request):
            return HttpResponse("Test")
    
        def get_urls(self):
            from django.conf.urls import url
            urls = super(MyAdminSite, self).get_urls()
            urls += [
                url(r'^custom_view/$', self.admin_view(self.custom_view))
            ]
            return urls
    
    admin_site = MyAdminSite()
    
    
    @admin.register(SomeModel, site=admin_site)
    class SomeModelAdmin(admin.ModelAdmin):
        pass
    

    my_project/urls.py

    from django.conf.urls import url, include
    
    from my_app.admin import admin_site
    
    urlpatterns = [
        url(r'^admin/', admin_site.urls),
        ...
    ]
    

提交回复
热议问题