+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2020-03(62)

2020-04(60)

2020-05(24)

2020-06(39)

2020-07(23)

Django开发之Admin源码学习

发布于2020-06-13 19:03     阅读(391)     评论(0)     点赞(11)     收藏(3)


0

1

2

3

4

5

6

admin 源码:

1.注册 admin.py

    admin.site.register(Book, BookConfig)

    源码:
        class AdminSite():
            def __init__(self, name='admin'):
                self._registry = {}

            def register(self, model, admin_class):
                if not admin_class:
                    admin_class = ModelAdmin

                self._registry[model] = admin_class(model, self)

        site = AdminSite()

2.设计url
如何通过model类变量获取该模型的字符串名称和该模型所在app的字符串名称:
print(">", model._meta.model_name)
print("
>", model._meta.app_label)

 def add(request):
    return HttpResponse('ok')

    def delete(request, id):
        print(id)
        return HttpResponse('ok')

    def change(request, id):
        return HttpResponse('ok')

    def list_view(request):
        return HttpResponse('ok')


    def get_urls2():
    temp = []

    temp.append(path('add/', views.add))
    temp.append(re_path(r'(\d+)/delete/', views.delete))
    temp.append(re_path(r'(\d+)/change/', views.change))
    temp.append(path('', views.list_view))

    return temp


    def get_urls():
        temp = []
        for model, admin_class_obj in admin.site._registry.items():
            # print('model', model)
            # class 'django.contrib.auth.models.Group'>
            # class 'django.contrib.auth.models.User'>
            # print("==>", model._meta.model_name)
            # print("==>", model._meta.app_label)
            model_name = model._meta.model_name
            app_label = model._meta.app_label
            temp.append(path('%s/%s/' % (app_label, model_name), (get_urls2(), None, None)))

        return temp


    def get_urls2():
        temp = []

        temp.append(path('add/', views.add))
        temp.append(re_path(r'(\d+)/delete/', views.delete))
        temp.append(re_path(r'(\d+)/change/', views.change))
        temp.append(path('', views.list_view))

        return temp


    urlpatterns = [
        path('king_admin/', (get_urls(), None, None)) ,
    ]
在ModelStark中:
    self.model: 用户当前访问的模型表
主要实现以下几个功能,最难的就是查看页面(其中涉及到分页和filter)
查看页面:
    表头
    表数据
    search
    action
    分页
    filter


增删改(modelForm)
title = Book._meta.get_field('title')  # 拿表中对应字段的对象
title.max_length

{"page":"12", "title_startwith":"py", "id__gt":"5"} 变为
"page=12&title_startwith=py&id__gt=5"
只需通过以下命令即可:
self.params.urlencode()

0

1

2

3

4

5

6

7

8

9



所属网站分类: 技术文章 > 博客

作者:9384vfnv

链接: https://www.pythonheidong.com/blog/article/414878/83c019f706ca297bfca5/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

11 0
收藏该文
已收藏

评论内容:(最多支持255个字符)