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組件

註冊html

admin流程
1.啓動(manage.py ——>settings ——>INSTALL_APPS ——>admin ——>admin.py )
2.註冊流程

 

在註冊的過程當中自定義一些內容 BookConfigpython

 

單例模式

__new__--->能夠實現改變類變量 + 節省內存--->啓動一個程序,在一個程序裏實現單例模式git

 

一個程序執行,屢次模塊導入,用到的都是同一個實例對象
 

模塊導入,要引的是模塊裏的對象,不是模塊裏的類數據庫

 

全部的admin.site都是一個單例對象django

 

URL一級分發

至關於 include寫到一個URL()裏app

_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類的對象。ide

用途是獲得admin組件裏展現的表格的表頭字段url

Django特有的方法:_meta能夠取出model名稱、app名稱、字段名稱、字段verbose_name名稱

 

自定義stark組件

設置啓動app掃描stark.py spa

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)
相關文章
相關標籤/搜索