Django内置Admin
一、Admin的运行原理:
admin相当于一个app,它的源码中预设admin/login等url.
admin.site.register(models.UserInfo)注册数据表原理:
在python manage.py runserver 时,自动调用所有app中的admin.py,然后调用site.register方法,site为源码中AdminSite()对象,然后判断register方法括号内的参数是否继承自ModelBase类,models.Model就继承于ModelBase,如果是,将它转换为可迭代对象,
然后通过for循环生成一个字典并保存:_registry = {
models.UserInfo: admin.ModelAdmin(models.UserInfo,admin.site)
models.UserGroup: admin.ModelAdmin(models.UserGroup,admin.site)
而当程序运行起来后,读取配置文件,ROOT_URLCONF = 'DjangoAdmin.urls', 会触发admin.site.urls执行,通过return的 self.get_urls()方法,
先注册预设的url,然后循环之前生成的字典_registry.items(),拼接生成每个models类单独的url地址,通过访问唯一生成的地址,
渲染成页面展示给用户,在include中的model_admin.urls方法则是通过分发add、change等路径 wrap一个个函数对数据表进行操作
for model, model_admin in self._registry.items(): urlpatterns += [ url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)), app01/userinfo/ ] if model._meta.app_label not in valid_app_labels: valid_app_labels.append(model._meta.app_label)
二、Admin的使用
from django.contrib import admin from app01 import models admin.site.register(models.UserInfo,admin.ModelAdmin) admin.site.register(models.UserGroup,admin.ModelAdmin) urlpatterns = [ url(r'^admin/', admin.site.urls), ] #基于装饰器 # @admin.register([models.UserInfo,]) # 第一个参数可以是列表 # class UserAdmin(admin.ModelAdmin): # # list_display = ('user', 'pwd',) # pass
5. list_display
list_display = ('user', 'email', yuhao)
内部原理:
from types import FunctionType def yuhao(): # print(obj.user) return '小于浩' list_display = ('user', 'email', yuhao) for item in list_display: if isinstance(item,FunctionType): print(item()) else: print(item)
...
15. 定制模板时
add_form_template = None
change_form_template = None
change_list_template = None
delete_confirmation_template = None
delete_selected_confirmation_template = None
object_history_template = None
from django.template.response import TemplateResponse
test_template = None
def test(request):
# print(models.UserInfo._meta.app_label)
# print(models.UserInfo._meta.model_name)
# if test_template:
# return render(request,test_template)
# else:
# return HttpResponse('...')
return TemplateResponse(request,[] or ['xiaohaohao.html','my_change_list.html'],{'k1':'v1'})
Admin开发: http://www.cnblogs.com/wupeiqi/articles/7444717.html