django admin, extending admin with custom views

前端 未结 4 1429
花落未央
花落未央 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:39

    This code below will override the default admin site to write your custom view.

    Works for Django >= 2.1 :

    ###myproject/admin.py

    from django.contrib import admin
    from django.http import HttpResponse
    
    class MyAdminSite(admin.AdminSite):
    
        def my_view(self, request): # your custom view function
            return HttpResponse("Test")
    
        def get_urls(self):
            from django.urls import path
    
            urlpatterns = super().get_urls()
            urlpatterns += [
                path('my_view/', self.admin_view(self.my_view))
            ]
            return urlpatterns
    

    ###myproject/apps.py

    from django.contrib.admin.apps import AdminConfig
    
    class MyAdminConfig(AdminConfig):
        default_site = 'myproject.admin.MyAdminSite'
    

    ###myproject/settings.py

    INSTALLED_APPS = [
        ...
        'myproject.apps.MyAdminConfig',  # replaces 'django.contrib.admin'
        ...
    ]
    

    Then go to http://127.0.0.1:8000/admin/my_view/

提交回复
热议问题