zoukankan      html  css  js  c++  java
  • S20_DAY23--课堂笔记

    今日笔记

    CRM
     
      1 权限
      2 stark组件(admin组件) 
      3 逻辑
     
    stark组件
     
        回顾admin:
            1 数据库迁移
            2 python manage.py createsuperuser
            3 在admin.py 注册model
            4 访问admin/app名称/model名称/操作
             
        admin流程:
         
             1 启动(settings---->installapp------>admin)
                
                def autodiscover():autodiscover_modules('admin', register_to=site)
                
             2 注册
                  admin.site : 单例对象
                   
                  class AdminSite():
                        def __init__(self, name='admin'):
                            self._registry = {} 
                             
                        def register(self, model, admin_class=None, **options):
                                if not admin_class:
                                        admin_class = ModelAdmin
                                         
                                self._registry[model] = admin_class(model, self)
                             
                  site=AdminSite()
                   
                  admin.site.register(Book)    #  site._registry:{Book:ModelAdmin(Book)}
                  admin.site.register(Publish) #  site._registry:{Book:ModelAdmin(Book),Publish:ModelAdmin(Publish)}
                   
                  # site._registry:{模型类:该模型类的配置类对象,........}
              
             3 设计url
              
                知识点: url()的使用:分发
                  
                            url(r'^index/', index), # 一旦匹配成功, index(request)
                              
                            urlpatterns = [
                                url(r'^admin/', admin.site.urls),
     
                                url(r'^yuan/', ([
                                      url(r'^test01/', ([
                                                  url(r'^test1_1/', test01),
                                                  url(r'^test1_2/', test01),
                                                        ],None,None)),
                                      url(r'^test02/', test02),
                                      url(r'^test03/', test03),
                                                ],None,None)),
                            ] 
                             
                应用:
                     
                    admin:
                         http://127.0.0.1:8000/admin/app01/book/
                         http://127.0.0.1:8000/admin/app01/book/add
                         http://127.0.0.1:8000/admin/app01/book/3/change
                         http://127.0.0.1:8000/admin/app01/book/3/deleter
                          
                     
                     
     
                   
        stark组件
         
      
           {
           <class 'app01.models.Book'>: <stark.service.sites.ModelAdmin object at 0x0000000004283240>,
           <class 'app01.models.Publish'>: <stark.service.sites.ModelAdmin object at 0x00000000042830B8>, 
           <class 'app01.models.Author'>: <stark.service.sites.ModelAdmin object at 0x0000000004283358>,
           n object at 0x0000000004283080>
           }
            
            
        增
        删
        改
        查  print(self.model) :  用户访问哪张表,self.model就是哪张表。
         
        查: 查看数据 表头 search action filter

    回顾admin组件

    注册

    admin流程
    1.启动(manage.py——>settings——>INSTALL_APPS——>admin——>admin.py )
    2.注册流程

    在注册的过程中自定义一些内容 BookConfig

     

    单例模式

    __new__--->可以实现改变类变量 + 节省内存--->启动一个程序,在一个程序里实现单例模式

    一个程序执行,多次模块导入,用到的都是同一个实例对象
     

    模块导入,要引的是模块里的对象,不是模块里的类

    所有的admin.site都是一个单例对象

    URL一级分发

    相当于 include写到一个URL()里

    _meta方法 

    from django.db import models
    
    # Create your models here.
    
    
    class Book(models.Model):
        title=models.CharField(max_length=32)
        price=models.DecimalField(max_digits=6,decimal_places=2)
        create_time=models.DateField()
        memo=models.CharField(max_length=32,default="")
    
        # book_obj.publish: 与这本书籍关联的出版社对象
        publish=models.ForeignKey(to="Publish",default=1)
        # book_obj.author.all():  与这本书关联的作者对象集合,Queryset []
        authors=models.ManyToManyField("Author") # 自动创建第三张表
    
        def __str__(self):
            return self.title

    price是类里面的变量名,赋予的值是models.DecimalField类的对象。

    用途是得到admin组件里展示的表格的表头字段

    Django特有的方法:_meta可以取出model名称、app名称、字段名称、字段verbose_name名称

    自定义stark组件

    设置启动app扫描stark.py 

    from django.apps import AppConfig
    from django.utils.module_loading import autodiscover_modules
    
    class StarkConfig(AppConfig):
        name = 'stark'
    
        def ready(self):
            autodiscover_modules('stark') # 执行每一个app下的stark.py
    stark/apps.py

    目录结构

    from stark.service.sites import site,ModelStark
    
    from app01.models import Book
    from app01.models import Publish
    from app01.models import Author
    
    
    
    
    class BookConfig(ModelStark):
    
    
        def display_authors(self, obj=None,is_header=False):
    
            if is_header:
                return "作者"
            s=[]
            for author in obj.authors.all():
                s.append(author.name)
    
            return " ".join(s)
    
    
        list_display = ["nid","title","price","publish","authors",]
    
    site.register(Book,BookConfig)
    
    
    
    site.register(Publish)
    site.register(Author)
    
    
    print(site._registry)
    app01-stark.py 
    from stark.service.sites import  site
    from app02.models import Food
    
    site.register(Food)
    print("------>",site._registry)
    app02-stark.py 

    from django.conf.urls import url
    
    from django.shortcuts import HttpResponse, render
    from django.utils.safestring import mark_safe
    
    class ModelStark():
        list_display = ["__str__",]
    
        def __init__(self, model, site):
            self.model = model
            self.site = site
    
        def edit(self, obj=None, is_header=False):
    
            if is_header:
                return "操作"
            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='%s/delete'>删除</a>" % obj.pk)
    
        def checkbox(self, obj=None, is_header=False):
            if is_header:
                return "选择"
            return mark_safe("<input type='checkbox' pk=%s>" % obj.pk)
    
        def add(self, request):
            return HttpResponse("add")
    
        def new_list_display(self):
    
            temp=[]
            temp.append(ModelStark.checkbox)
            temp.extend(self.list_display)
            temp.append(ModelStark.edit)
            temp.append(ModelStark.delete)
    
            return temp
    
    
        def list_view(self, request):
            print(self.model)
            data_list = self.model.objects.all()
            print("list_display", self.list_display)  #  ["nid","title","price",edit]
            # 处理表头
            # header_list=["ID","名称","价格"]
            header_list=[]
            for field in self.new_list_display():
                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)
                header_list.append(val)
    
            # 处理表单数据
    
    
    
            new_data_list = []
            for obj in data_list:
                temp = []
                for field in self.new_list_display():  #   ["nid","title","price","authors",edit]    ['__str__']     ["title","price"]
                    if isinstance(field,str):
                        try:
                            from django.db.models.fields.related import ManyToManyField
                            field_obj=self.model._meta.get_field(field)
                            if isinstance(field_obj,ManyToManyField):
                                l=[]
                                for i in getattr(obj,field).all():
                                    l.append(str(i))
                                val=",".join(l)
    
                            else:
                                val = getattr(obj, field)
                                print("val",val)
                        except Exception as e:
                            val = getattr(obj, field)
    
                    else:
                        val=field(self,obj)
                    temp.append(val)
    
    
                new_data_list.append(temp)
    
            '''
            new_data_list=[
               [1 "python",121,"<a href='/stark/app01/book/1/change'>编辑</a>"],
               
               [2,"go",124,"<a href='/stark/app01/book/2/change'>编辑</a>"],
           ]
    
           
           '''
    
            return render(request, "list_view.html", locals())
    
        def change(self, request, id):
            return HttpResponse("change")
    
        def delete_view(self, request, id):
            return HttpResponse("delete_view")
    
        def get_urls2(self):
    
            temp = [
                url("^add/$", self.add),
                url("^$", self.list_view),
                url("^(d+)/change/$", self.change),
                url("^(d+)/delete/$", self.delete_view),
            ]
    
            return temp
    
        @property
        def urls2(self):
            return self.get_urls2(), None, None
    
    
    class StarkSite():
        def __init__(self, ):
            self._registry = {}
    
        # 一级分发
    
        def get_urls(self):
            temp = []
    
            for model, model_class_obj in self._registry.items():  # {Book:ModelAdmin(Book),Publish:ModelAdmn(Publish),....}
    
                app_name = model._meta.app_label
                model_name = model._meta.model_name
                temp.append(url(r"%s/%s/" % (app_name, model_name), model_class_obj.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 = ModelStark
    
            self._registry[model] = admin_class(model, self)
    
    
    site = StarkSite()
    
    '''
            temp.append(url(r"app01/book",ModelAdmin(Book).urls2))
            temp.append(url(r"app01/publish",ModelAdmin(Publish).urls2))
    
    
            '''
    stark/service/sites.py

    from django.utils.safestring import mark_safe

    不要写死URL 

    herf=%s/add ,%(obj.pk)前面没有/,django会利用当前路径自动补全

    作业:(不要使用上面的自动补全路径)

    增删改__路径:利用反向解析灵活实现book/publish/author路径

    显示多对多关系

    new_list_display-->temp.extends(list_display)
  • 相关阅读:
    hadoop之hdfs架构详解
    hadoop之hdfs命令详解
    hadoop高可用安装和原理详解
    mysql事务
    mysql之innodb-锁
    [转]网络基本功02-细说交换机
    python随用随学20200221-生成器中的send(),throw()和close()方法
    python随用随学20200118-函数的高级特性
    [转载]网络基本功01-细说网络传输
    selenium+chrome抓取淘宝宝贝-崔庆才思路
  • 原文地址:https://www.cnblogs.com/shangdelu/p/9166759.html
Copyright © 2011-2022 走看看