django admin, extending admin with custom views

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

    For Django 1.4+ here is the solution:

    from django.conf.urls import url
    from django.contrib import admin
    from .models import MyModel
    
    
    class MyAdmin(admin.ModelAdmin):
        list_display = (...)
    
        def custom_admin_view(self, request):
            # your logic here
            if request.method == 'POST':
                ...
            else:
                ...
            return HttpResponse(...)
    
        def get_urls(self):
            additional_urls = [
                url(r'^custom/$', self.admin_site.admin_view(self.custom_admin_view), name='custom')
            ]
            # append your custom URL BEFORE default ones
            return additional_urls + super().get_urls()
    
    
    admin.site.register(MyModel, MyAdmin)
    

    It's important to append your custom URL before all others. Otherwise you might get redirect to admin change_view instead.

提交回复
热议问题