admin

1、启动开发服务器,然后在浏览器中访问 http://127.0.0.1:8000/admin/,得到登陆界面,你可以通过命令 python manage.py createsuperuser 来创建超级用户。

2、admin.py(app01有4张表,app02有1张表)

from django.contrib import admin
from .models import *

class BookConfig(admin.ModelAdmin):
    list_display=["id","user","room","date","time_id"] # 默认是__str__,不能放多对多字段
    list_filter=["user","room","date"]   # 页面右边会出现一个小框,刷选相关

    list_display_links=["user"]   # 点击进去可以编辑
    list_editable=["room"]  # 可以直接在查看页面编辑,可以和 links里面的重复

    #date_hierarchy = "date"
    #fields=["user","room"]
    #exclude=["user","room"]

    ordering=["date","time_id"]     # ordering,列表时,数据排序规则
    search_fields=["user","tel",]     #  模糊查找

    # 定制Action行为具体方法
    def func(self, request, queryset):
        print(self, request, queryset)
        print(request.POST.getlist('_selected_action'))
        queryset.update(date="2012-12-12")
    
    func.short_description = "批量初始化操作"
    # func.short_description = "中文显示自定义Actions"
    actions = [func, ]



admin.site.register(Book,BookConfig)  # 如果无BookConfig,默认走ModelAdmin
# print("11111111111111111111",admin.site._registry)
admin.site.register(UserInfo,UserConfig)
admin.site.register(Room)
admin.site.register(GF)
# print("2222222222222",admin.site._registry)

 admin.site._registry      print具体内容!!!!!!!!

 1 a1 ={<class 'django.contrib.auth.models.Group'>: <django.contrib.auth.admin.GroupAdmin object at 0x000001D31F9CDCC0>,
 2     <class 'app01.models.Book'>: <app01.admin.BookConfig object at 0x000001D31F9FC9E8>}
 3 a2= {<class 'django.contrib.auth.models.Group'>: <django.contrib.auth.admin.GroupAdmin object at 0x000001D31F9CDCC0>,
 4     <class 'app01.models.Book'>: <app01.admin.BookConfig object at 0x000001D31F9FC9E8>,
 5     <class 'app01.models.UserInfo'>: <app01.admin.UserConfig object at 0x000001D31FA0C588>,
 6     <class 'app01.models.Room'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C470>,
 7     <class 'app01.models.GF'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C5C0>}
 8 
 9 a12= {<class 'django.contrib.auth.models.Group'>: <django.contrib.auth.admin.GroupAdmin object at 0x000001D31F9CDCC0>,
10     <class 'app01.models.Book'>: <app01.admin.BookConfig object at 0x000001D31F9FC9E8>,
11     <class 'app01.models.UserInfo'>: <app01.admin.UserConfig object at 0x000001D31FA0C588>,
12     <class 'app01.models.Room'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C470>,
13     <class 'app01.models.GF'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C5C0>,
14     <class 'app02.models.Book'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C860>}
print(admin.site._registry)

      admin源码解析

1、单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。

比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象
某一个类只有一个实例存在

在 Python 中,我们可以用多种方法来实现单例模式:

  • 使用模块
  • 使用 __new__
  • 使用装饰器(decorator)
  • 使用元类(metaclass)

1.1、__new__

 1 class Singleton(object):
 2     _instance = None
 3     def __new__(cls, *args, **kw):
 4         if not cls._instance:
 5             cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
 6         return cls._instance
 7 
 8 class MyClass(Singleton):
 9     a = 1
10 
11 
12 one = MyClass()
13 # print(one.a)                   #   1  
14 one.a=3
15 # print(one.a)                   #  3
16 
17 two = MyClass()
18 print(two.a)                      #   3  
19 
20 print(one==two)                #  True
21 print(id(one),id(two))           #  2663784027136 2663784027136
__new__

1.2、模块(Python 的模块就是天然的单例模式)

#   mysingleton.py
class My_Singleton(object):
    x =12
    def foo(self):
        print(self.x)


my_singleton = My_Singleton()
print(id(my_singleton))

print("OK")
mysingleton.py
from mysingleton import my_singleton

def foo():

    print(id(my_singleton))
func.py
from mysingleton import my_singleton

print(id(my_singleton))

from mysingleton import my_singleton

print(id(my_singleton))

from func import *
foo()


"""
1852889535264
OK
1852889535264
1852889535264
1852889535264
"""

print("其他情况,不同引入")
from mysingleton import My_Singleton

a=My_Singleton()
b=My_Singleton()

print(id(a))
print(id(b))
"""
1832133040112
1832133039216
"""
main.py
    for model,admin_class_obj in admin.site._registry.items():
         print("model",model) # 所有的注册模型表


         # < class 'app01.models.Book'>----->     "book"  "app01"
         # < class 'app01.models.Room'>----->     "room"  "app01"
         # print("===>",model._meta.model_name)
         # print("===>",model._meta.app_label)

         model_name=model._meta.model_name
         app_label=model._meta.app_label

         temp.append(url(  r"%s/%s/"%(app_label,model_name) ,    (  get_urls2()  ,None  ,None  )    )   )

    print(temp)
    """
    temp=
    [<RegexURLResolver <RegexURLPattern list> (None:None) auth/group/>, 
    <RegexURLResolver <RegexURLPattern list> (None:None) app01/book/>, 
    <RegexURLResolver <RegexURLPattern list> (None:None) app01/userinfo/>, 
    <RegexURLResolver <RegexURLPattern list> (None:None) app01/room/>, 
    <RegexURLResolver <RegexURLPattern list> (None:None) app01/gf/>, 
    <RegexURLResolver <RegexURLPattern list> (None:None) app02/book/>]
    """
    return temp
admin.site._registry提取model_name和app_label

2、注册 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()
app0102= 
    {<class 'django.contrib.auth.models.Group'>: <django.contrib.auth.admin.GroupAdmin object at 0x000001D31F9CDCC0>,
    <class 'app01.models.Book'>: <app01.admin.BookConfig object at 0x000001D31F9FC9E8>,
    <class 'app01.models.UserInfo'>: <app01.admin.UserConfig object at 0x000001D31FA0C588>,
    <class 'app01.models.Room'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C470>,
    <class 'app01.models.GF'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C5C0>,
    <class 'app02.models.Book'>: <django.contrib.admin.options.ModelAdmin object at 0x000001D31FA0C860>}
admin.site._registry

model._meta.model_name ---> 表名
model._meta.app_label ---> app名字

3、URL

3.1 基本使用

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),

    url(r"^yuan/",([  ],None,None)),  #  注意形式,本质!!!
]

    路由分发

    url(r"^yuan/", ([
                        url(r'^test01/', ([
                                              url(r'^test04/', test04),
                                              url(r'^test05/', test05),
                                          ], None, None)),
                        url(r'^test02/', test02),
                        url(r'^test03/', test03),
                    ], None, None)
        )
urlpatterns=[
    url(r"^yuan/",([
        url(r"^test01/",test01")
        ],None,None,))
]

yuan/test01/  如果有^ yuan后面必须是test01 ,没有^,只要后面是test01就可以。
注意点

 

mark

def add(request):
    return HttpResponse("add")
def delete(request,id):
    return HttpResponse("delete")
def change(request,id):
    return HttpResponse("change")
def list_view(request):
    return HttpResponse("list_view")


def get_urls2():

    temp=[]
    temp.append(url(r"^add/",add))
    temp.append(url(r"^(\d+)/delete/",delete))
    temp.append(url(r"^(\d+)/change/",change))
    temp.append(url(r"^$",list_view))
    return temp

def get_urls():


    temp=[]
    print("_registry",admin.site._registry)

    for model,admin_class_obj in admin.site._registry.items():
         print("model",model) # 所有的注册模型表

         # < class 'app01.models.Book'>----->     "book"  "app01"
         # < class 'app01.models.Room'>----->     "room"  "app01"
         # print("===>",model._meta.model_name)
         # print("===>",model._meta.app_label)

         model_name=model._meta.model_name
         app_label=model._meta.app_label
         temp.append(url(r"%s/%s/"%(app_label,model_name),(get_urls2(),None,None)))

    return temp





urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^login/', views.login),
    url(r'^book/', views.book),


    url(r"^yuan/",(get_urls(),None,None))


]
待补充0503

http://www.cnblogs.com/yuanchenqi/articles/8323452.html#_label0

posted @ 2018-04-17 09:04  nick560  阅读(262)  评论(0编辑  收藏  举报