Django - custom admin page not related to a model

2019-04-12 09:49发布

I am using Django 1.7 with Mezzanine. I would like to have some page in admin, where the staff can call some actions (management commands etc.) with buttons and other control elements.

I would also like to avoid creating new model, or manually create a template and add link to it (if possible).

What is the most common/clean ways how to achieve that?

2条回答
爷、活的狠高调
2楼-- · 2019-04-12 10:30

ModelAdmin.get_urls let you add a url to the admin url's. So you can add your own view like this:

class MyModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super(MyModelAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^my_view/$', self.my_view)
        )
        return my_urls + urls

    def my_view(self, request):
        # custom view which should return an HttpResponse
        pass

https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls

I didn't try this out, but it seems to me that you can subclass a build-in admin view and let your custom template extend the build-in admin templates.

查看更多
ら.Afraid
3楼-- · 2019-04-12 10:34

Actually it is simpler. Just before urlpatterns in urls.py patch admin urls like that:

def get_admin_urls(urls):
    def get_urls():
        my_urls =  patterns('',
           url(r'^$', YourCustomView,name='home'), 
        )
        return my_urls + urls
    return get_urls

admin.autodiscover()

admin_urls = get_admin_urls(admin.site.get_urls())
admin.site.get_urls = admin_urls
查看更多
登录 后发表回答