• 10.10xadmin


    2018-10-10 15:11:55

    这几天讲的是xadmin插件

    就是把表单,数据内容封装到类里面,简化的增删改查步骤!

    放上源代码:

    app01/xadim.py

    from django.contrib import admin
    
    # Register your models here.
    
    
    from Xadmin.service.Xadmin import site,ModelXadmin
    
    print("app01 Xadmin")
    
    from app01.models import *
    from django.utils.safestring import  mark_safe
    
    class BookConfig(ModelXadmin):
        def edit(self,obj=None,is_header=False):
            if is_header:
                return "操作"
            # 反向解析:url
            return mark_safe("<a href='%s/change/'>编辑</a>"%obj.pk)
    
        def delete(self,obj=None,is_header=False):
    
            if is_header:
                return "操作"
    
            return mark_safe("<a href=''>删除</a>")
    
        def check(self,obj=None,is_header=False):
            if is_header:
                return "选择"
    
            return mark_safe("<input type='checkbox'>")
    
    
        list_display=[check,"nid","title","publish",edit,delete]
        #list_display=["nid","title","publish"]
    
    site.register(Book,BookConfig)
    
    
    
    site.register(Publish)
    site.register(Author)
    site.register(AuthorDetail)

    app02/xadmin.py

    from Xadmin.service.Xadmin import site,ModelXadmin
    
    from app02.models import *
    
    site.register(Order)
    
    
    class FoodConfig(ModelXadmin):
        list_display = ["id","title"]
    site.register(Food,FoodConfig)
    
    print("_registry",site._registry)

    Xadmin/service/xadmin.py

    from django.conf.urls import url
    from django.shortcuts import HttpResponse,render,redirect
    class ModelXadmin(object):
        list_display=["__str__",]
        def __init__(self,model,site):
    
            self.model=model
            self.site=site
    
        def list_view(self, request):
            print("self.model", self.model) # 用户访问哪张表,self.model就是谁。
            model_name=self.model._meta.model_name
            data_list = self.model.objects.all()
            print("list_display:",self.list_display) ## ['title', 'prcie']
    
            # 处理表头
            #header_list=["ID","书籍名称","出版社"]
            header_list=[]
    
            for field in self.list_display: # [check,"nid","title","publish",edit,delete]
                if isinstance(field,str):
                    if field=="__str__":
                        val= self.model._meta.model_name.upper()
                    else:
                        field_obj=self.model._meta.get_field(field)
                        val=field_obj.verbose_name
    
                else:
                    val=field(self,is_header=True)  #  获取表头,传is_header=True
    
                header_list.append(val)
            # 处理表单数据
            new_data_list=[]
            for obj in data_list:  #   data_list [book_obj,book_obj2,...]
    
                temp=[]
                for field in self.list_display: # ['title', 'prcie',edit,delete]
                    if isinstance(field,str):
                        val=getattr(obj,field)
                    else:
                        val=field(self,obj)
    
                    temp.append(val)
    
                new_data_list.append(temp)
    
            '''
            new_data_list=[
                ["北京折叠",122,<a href=''>编辑</a>,<a href=''>删除</a>],
                ["三体", 222,<a href=''>编辑</a>,<a href=''>删除</a>],
            ]
            '''
    
            return render(request, 'list_view.html', {"new_data_list": new_data_list,"model_name":model_name,"header_list":header_list})
    
        def add_view(self, request):
            return render(request, 'add_view.html')
    
        def change_view(self, request, id):
            return render(request, 'change_view.html')
    
        def delete_view(self, request, id):
            return render(request, 'delete_view.html')
    
        def get_urls2(self):
            temp = []
    
            temp.append(url(r"^$", self.list_view))
            temp.append(url(r"^add/$", self.add_view))
            temp.append(url(r"^(d+)/change/$", self.change_view))
            temp.append(url(r"^(d+)/delete/$", self.delete_view))
    
            return temp
    
        @property
        def urls2(self):
            return self.get_urls2(), None, None
    
    
    class XadminSite(object):
    
        def __init__(self, name='admin'):
            self._registry = {}
    
    
        def get_urls(self):
    
            print(self._registry)  # {Book:modelAdmin(Book),.......}
    
            temp = []
            for model, admin_class_obj in self._registry.items():
                # 获取当前循环的model的字符串与所在app的字符串
                app_name = model._meta.app_label     #  "app01"
                model_name = model._meta.model_name  # "book"
    
                temp.append(url(r'^{0}/{1}/'.format(app_name, model_name),admin_class_obj.urls2), )
    
    
                '''
                url(r"app01/book",ModelXadmin(Book,site).urls2)
                url(r"app01/publish",ModelXadmin(Publish,site).urls2)
                url(r"app02/order",ModelXadmin(Order,site).urls2)
                
                '''
            return temp
    
        @property
        def urls(self):
            return self.get_urls(),None,None
    
        def register(self, model, admin_class=None, **options):
            if not admin_class:
                     admin_class = ModelXadmin
    
            self._registry[model] = admin_class(model, self) # {Book:ModelAdmin(Book),Publish:ModelAdmin(Publish)}
    
    site=XadminSite()
  • 相关阅读:
    [LeetCode] 1268. Search Suggestions System
    [LeetCode] 907. Sum of Subarray Minimums
    [LeetCode] 2034. Stock Price Fluctuation
    [LeetCode] 792. Number of Matching Subsequences
    [LeetCode] 212. Word Search II
    [LeetCode] 828. Count Unique Characters of All Substrings of a Given String
    [LeetCode] 408. Valid Word Abbreviation
    [LeetCode] 1161. Maximum Level Sum of a Binary Tree
    [LeetCode] 1152. Analyze User Website Visit Pattern
    [LeetCode] 636. Exclusive Time of Functions
  • 原文地址:https://www.cnblogs.com/zhen1996/p/9766527.html
Copyright © 2020-2023  润新知