回到顶部

Contents

Django admin 注册自己的路由(How To Add Custom Views To Django Admin)

目的效果

通过 admin.py 在 Django 后台注册自己的路由(对应自己的视图)

实现代码

要在一个 app 里面的 admin.py 添加如下代码(实际上就一个简化的 model)

# django2\apps\business\admin.py

from django.contrib import admin
from django.contrib.admin import AdminSite
from django.http import HttpResponse
from django.urls import path

from .models import *
from .views import index


# Register your models here.

class DummyModel(models.Model):
    class Meta:
        verbose_name = "自定义路由"
        verbose_name_plural = '自定义路由'
        app_label = 'business'


def my_custom_view(request):
    return HttpResponse('自定义路由,写自己的内容')


class DummyModelAdmin(admin.ModelAdmin):
    model = DummyModel

    def get_urls(self):
        view_name = '{}_{}_changelist'.format(
            self.model._meta.app_label, self.model._meta.model_name)
        return [
            path('settings/', my_custom_view, name=view_name),
        ]


admin.site.register(DummyModel, DummyModelAdmin)

 

# django2\apps\business\__init__.py
default_app_config = "apps.business.apps.BusinessConfig"

 

# django2\apps\business\apps.py
from django.apps import AppConfig


class BusinessConfig(AppConfig):
    name = 'apps.business'
    verbose_name = "客户例子"

实现效果

参考文档

https://github.com/AnjaneyuluBatta505/learnbatta/blob/master/django/django_admin_custom_view/sample/admin.py


^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!
前一篇: django-import-export 资料收集(Django 导入导出数据)
下一篇: 域名购买域名出售
captcha