Django - Admin
一、admin组件使用
Django 提供了基于 web 的管理工具。
Django 自动管理工具是 django.contrib 的一部分。你可以在项目的 settings.py 中的 INSTALLED_APPS 看到它:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]
django.contrib是一套庞大的功能集,它是Django基本代码的组成部分。
1. 激活管理工具:
通常我们在生成项目时会在 urls.py 中自动设置好,
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
当这一切都配置好后,Django 管理工具就可以运行了。
2. 使用管理工具:
启动开发服务器,然后在浏览器中访问 http://127.0.0.1:8000/admin/,得到登陆界面,你可以通过命令 python manage.py createsuperuser 来创建超级用户。
为了让 admin 界面管理某个数据模型,我们需要先注册该数据模型到 admin
from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class GF(models.Model): name = models.CharField(max_length=32) age = models.CharField(max_length=32) def __str__(self): return self.name class UserInfo(AbstractUser): tel = models.CharField(max_length=32) gf = models.ManyToManyField("GF") class Room(models.Model): """ 会议室表 """ caption = models.CharField(max_length=32) num = models.IntegerField() # 容纳人数 def __str__(self): return self.caption class Book(models.Model): """ 会议室预订信息 """ user = models.ForeignKey("UserInfo", on_delete=models.CASCADE) room = models.ForeignKey("Room", on_delete=models.CASCADE) date = models.DateField() time_choice = ( (1,'8:00'), (2,'9:00'), (3,'10:00'), (4,'11:00'), (5,'12:00'), (6,'13:00'), (7,'14:00'), (8,'15:00'), (9,'16:00'), (10,'17:00'), (11,'18:00'), (12,'19:00'), (13,'20:00'), ) time_id = models.IntegerField(choices=time_choice) class Meta: unique_together = ( ('room','date','time_id'), ) def __str__(self): return str(self.user)+'预订了'+str(self.room)
from django.db import models # Create your models here. class Author(models.Model): name=models.CharField( max_length=32) age=models.IntegerField() def __str__(self): return self.name class Publish(models.Model): name=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): title = models.CharField( max_length=32) publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) publisher=models.ForeignKey(to="Publish") authors=models.ManyToManyField(to='Author') def __str__(self): return self.title
3. admin的定制:
在admin.py中只需要将Mode中的某个类注册,即可在Admin中实现增删改查的功能,如:
admin.site.register(models.UserInfo)
但是,这种方式比较简单,如果想要进行更多的定制操作,需要利用ModelAdmin进行操作,如:
方式一:
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',)
admin.site.register(models.UserInfo, UserAdmin)
方式二:
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd',)
ModelAdmin中提供了大量的可定制功能,如
1. list_display,列表时,定制显示的列。
@admin.register(models.UserInfo) class UserAdmin(admin.ModelAdmin): list_display = ('user', 'pwd', 'xxxxx') def xxxxx(self, obj): return "xxxxx"
2. list_display_links,列表时,定制列可以点击跳转。
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd', 'xxxxx')
list_display_links = ('pwd',)
3. list_filter,列表时,定制右侧快速筛选。
4. list_select_related,列表时,连表查询是否自动select_related
5. list_editable,列表时,可以编辑的列
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
list_display = ('user', 'pwd','ug',)
list_editable = ('ug',)
6. search_fields,列表时,模糊搜索的功能
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
search_fields = ('user', 'pwd')
7. date_hierarchy,列表时,对Date和DateTime类型进行搜索
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
date_hierarchy = 'ctime'
8 inlines,详细页面,如果有其他表和当前表做FK,那么详细页面可以进行动态增加和删除
class UserInfoInline(admin.StackedInline): # TabularInline
extra = 0
model = models.UserInfo
class GroupAdminMode(admin.ModelAdmin):
list_display = ('id', 'title',)
inlines = [UserInfoInline, ]
9 action,列表时,定制action中的操作
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
# 定制Action行为具体方法
def func(self, request, queryset):
print(self, request, queryset)
print(request.POST.getlist('_selected_action'))
func.short_description = "中文显示自定义Actions"
actions = [func, ]
# Action选项都是在页面上方显示
actions_on_top = True
# Action选项都是在页面下方显示
actions_on_bottom = False
# 是否显示选择个数
actions_selection_counter = True
10 定制HTML模板
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
11 raw_id_fields,详细页面,针对FK和M2M字段变成以Input框形式
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
raw_id_fields = ('FK字段', 'M2M字段',)
12 fields,详细页面时,显示字段的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fields = ('user',)
13 exclude,详细页面时,排除的字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
exclude = ('user',)
14 readonly_fields,详细页面时,只读字段
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('user',)
15 fieldsets,详细页面时,使用fieldsets标签对数据进行分割显示
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
fieldsets = (
('基本数据', {
'fields': ('user', 'pwd', 'ctime',)
}),
('其他', {
'classes': ('collapse', 'wide', 'extrapretty'), # 'collapse','wide', 'extrapretty'
'fields': ('user', 'pwd'),
}),
)
16 详细页面时,M2M显示时,数据移动选择(方向:上下和左右)
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
filter_vertical = ("m2m字段",) # 或filter_horizontal = ("m2m字段",)
17 ordering,列表时,数据排序规则
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
ordering = ('-id',)
或
def get_ordering(self, request):
return ['-id', ]
18. radio_fields,详细页面时,使用radio显示选项(FK默认使用select)
radio_fields = {"ug": admin.VERTICAL} # 或admin.HORIZONTAL
19 form = ModelForm,用于定制用户请求时候表单验证
from app01 import models
from django.forms import ModelForm
from django.forms import fields
class MyForm(ModelForm):
others = fields.CharField()
class Meta:
model = models = models.UserInfo
fields = "__all__"
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
form = MyForm
20 empty_value_display = "列数据为空时,显示默认值"
@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):
empty_value_display = "列数据为空时,默认显示"
list_display = ('user','pwd','up')
def up(self,obj):
return obj.user
up.empty_value_display = "指定列数据为空时,默认显示"
from django.contrib import admin # Register your models here. from .models import * @admin.register(Book) class BookConfig(admin.ModelAdmin): # list_display = ('__str__',) # 不能放 多对多 字段! list_display = ['id', 'user', 'room', 'date', 'time_id'] list_display_links = ['user',] list_filter = ['user', 'room', 'date'] # 比较难 list_editable = ['room'] # The value of 'room' cannot be in both 'list_editable' and 'list_display_links'. date_hierarchy = "date" # 定制Action行为具体方法 def func(self,request,queryset): print(self,request,queryset) queryset.update(date='2012-12-12') func.short_description = "批量初始化操作" actions = [func,] # fields = ['user','room'] # 只显示 # exclude = ['user','room'] # 不显示 readonly_fields = ['user', 'room'] # 只读 # ordering = ['id','date', 'time_id'] ordering = ['-date'] class UserConfig(admin.ModelAdmin): # list_display = ['username', 'tel', 'gf'] """ 'list_display[2]' must not be a ManyToManyField. """ list_display = ['username', 'tel'] list_filter = ['gf','username'] search_fields = ['username', 'tel', ] # 只能放 普通字段 admin.site.register(UserInfo,UserConfig) # admin.site.register(Book,admin_class=BookConfig) admin.site.register(Room) admin.site.register(GF)
from django.contrib import admin # Register your models here. from .models import * class BookInline(admin.StackedInline): # TabularInline extra = 0 model = Book class BookAdmin(admin.ModelAdmin): list_display = ("title",'publishDate', 'price',"foo","publisher") list_display_links = ('publishDate',"price") list_filter = ('price',) list_editable=("title","publisher") search_fields = ('title',) date_hierarchy = 'publishDate' preserve_filters=False def foo(self,obj): return obj.title+str(obj.price) # 定制Action行为具体方法 def func(self, request, queryset): print(self, request, queryset) print(request.POST.getlist('_selected_action')) func.short_description = "中文显示自定义Actions" actions = [func, ] # Action选项都是在页面上方显示 actions_on_top = True # Action选项都是在页面下方显示 actions_on_bottom = False # 是否显示选择个数 actions_selection_counter = True change_list_template="my_change_list_template.html" class PublishAdmin(admin.ModelAdmin): list_display = ('name', 'email',) inlines = [BookInline, ] admin.site.register(Book, BookAdmin) # 第一个参数可以是列表 admin.site.register(Publish,PublishAdmin) admin.site.register(Author)
二、单例模式
单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。
在 Python 中,我们可以用多种方法来实现单例模式:
-
使用模块
-
使用
__new__
-
使用装饰器(decorator)
-
使用元类(metaclass)
1. 使用 __new__
为了使类只能出现一个实例,我们可以使用 __new__
来控制实例的创建过程,代码如下:
class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1
在上面的代码中,我们将类的实例和一个类变量 _instance
关联起来,如果 cls._instance
为 None 则创建实例,否则直接返回 cls._instance
。
执行情况如下:
>>> one = MyClass() >>> two = MyClass() >>> one == two True >>> one is two True >>> id(one), id(two) (4303862608, 4303862608)
class Person(object): def __init__(self,name,age): self.name = name self.age = age alex = Person('alex',34) egon = Person('egon',36) # 单例模式,一个类允许 实例一个对象 # 为什么这么做,为了数据统一 # 类:封装数据的组织形式 # 例如 配置文件,可以写成一个类,单例 class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1 one = MyClass() one.a = 3 two = MyClass() print(two.a) # 3 同一块内存 print(one==two) print(id(one),id(two)) class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs) return cls._instance class MyClass(Singleton): a = 1 one = MyClass() two = MyClass() one.a=3 print(id(one),id(two)) print(two.a) print(MyClass.mro())
2. 使用模块
其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc
文件,当第二次导入时,就会直接加载 .pyc
文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:
# mysingleton.py class My_Singleton(object): x = 12 def foo(self): print(self.x) my_singleton = My_Singleton() print('ok')
将上面的代码保存在文件 mysingleton.py
中,然后这样使用:
from mysingleton import my_singleton my_singleton.foo()
# # -*- coding:utf-8 -*- # from mysingleton import my_singleton # # # pyc 中间 临时文件 # # # my_singleton.foo() # print(id(my_singleton)) # # from mysingleton import my_singleton # # # # 在找 不会加载 第二遍 去临时 pyc 拿 # # # my_singleton.foo() # print(id(my_singleton)) # # # from func import * # foo() #三个id 会一样吗?? 一样,一次程序的执行, # # """ # ok # 2341951012992 # 2341951012992 # 2341951012992 # """ # # # """ # 12 # 2664635842288 # 12 # 2664635842288 # # 为什么内存地址一样 # # python 自己的玩法, python 在导模块 就执行代码 # """ from mysingleton import my_singleton,My_Singleton a = My_Singleton() b = My_Singleton() print(id(a),id(b)) # 2306139672928 2306139673096 # 不一样,类实例化, # 单例 是从模块里 哪一个实例对象 print(id(my_singleton),id(my_singleton)) # 2310426005856 2310426005856 一样,
from mysingleton import my_singleton def foo(): print(id(my_singleton))
注:python 自己的玩法, python 在导模块时,就执行代码;
三、admin源码解析
<1> 循环加载执行所有已经注册的app中的admin.py文件
def autodiscover():
autodiscover_modules('admin', register_to=site)
<2> 执行代码
#admin.py
class BookAdmin(admin.ModelAdmin):
list_display = ("title",'publishDate', 'price')
admin.site.register(Book, BookAdmin)
admin.site.register(Publish)
<3> admin.site
这里应用的是一个单例模式,对于AdminSite类的一个单例模式,执行的每一个app中的每一个admin.site都是一个对象
<4> 执行register方法
admin.site.register(Book, BookAdmin)
admin.site.register(Publish)
class ModelAdmin(BaseModelAdmin):pass
def register(self, model_or_iterable, admin_class=None, **options):
if not admin_class:
admin_class = ModelAdmin
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
思考:在每一个app的admin .py中加上
print(admin.site._registry) # 执行结果?
到这里,注册结束!
<5> admin的URL配置
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
class AdminSite(object):
def get_urls(self):
from django.conf.urls import url, include
urlpatterns = []
# Add in each model's views, and create a list of valid URLS for the
# app_index
valid_app_labels = []
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)),
]
if model._meta.app_label not in valid_app_labels:
valid_app_labels.append(model._meta.app_label)
return urlpatterns
@property
def urls(self):
return self.get_urls(), 'admin', self.name
<6> url()方法的扩展应用
from django.shortcuts import HttpResponse
def test01(request):
return HttpResponse("test01")
def test02(request):
return HttpResponse("test02")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^yuan/', ([
url(r'^test01/', test01),
url(r'^test02/', test02),
],None,None)),
]
扩展优化
from django.conf.urls import url,include
from django.contrib import admin
from django.shortcuts import HttpResponse
def change_list_view(request):
return HttpResponse("change_list_view")
def add_view(request):
return HttpResponse("add_view")
def delete_view(request):
return HttpResponse("delete_view")
def change_view(request):
return HttpResponse("change_view")
def get_urls():
temp=[
url(r"^$".format(app_name,model_name),change_list_view),
url(r"^add/$".format(app_name,model_name),add_view),
url(r"^\d+/del/$".format(app_name,model_name),delete_view),
url(r"^\d+/change/$".format(app_name,model_name),change_view),
]
return temp
url_list=[]
for model_class,obj in admin.site._registry.items():
model_name=model_class._meta.model_name
app_name=model_class._meta.app_label
# temp=url(r"{0}/{1}/".format(app_name,model_name),(get_urls(),None,None))
temp=url(r"{0}/{1}/".format(app_name,model_name),include(get_urls()))
url_list.append(temp)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^yuan/', (url_list,None,None)),
]
https://www.cnblogs.com/yuanchenqi/articles/8323452.html
权限 会议室预订 admin与stark admin怎么用,怎么写? 1.admin 不够灵活,不知怎么写,没法扩展!! 2.stark怎么用 看源码 怎么去利用 构建自己的架构!! stark 难点!! 用一个类 来实现? 封装 继承 多态 一堆 面向 面向对象 重点:面向对象,网络编程,web应用 迭代器生成器,python独有的!!数据库! admin 使用,再看源码!! stark crm restframework 3-4 vue 3-4 路飞 爬虫,linux flask ---------------------------------- 知识点1: url()的使用 情况1:url(r'^book/', views.book), # book(request) 情况2 分发: 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) ) 知识点2: 单例模式 生成单例模式的方式: (1)使用 __new__ (2)使用模块 class A() pass a=A() admin源码: 1 注册 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() 2 设计url 如何通过model类变量获取该模型的字符串名称和该模型所在app的字符串名称: print("===>", model._meta.model_name) print("===>", model._meta.app_label) ################################################################### 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)) ] 上节回顾 1 admin的使用 list_display list_display_links search_fields list_filter action class BookConfig(admin.ModelAdmin): list_display list_display_links search_fields list_filter action admin.site.register(Book,BookConfig) 2 知识点 url()的使用 情况1:url(r'^book/', views.book), # book(request) 情况2 分发: 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) ) 单例模式 生成单例模式的方式: (1)使用 __new__ (2)使用模块 class A() pass a=A() admin源码: 1 启动文件 class StarkConfig(AppConfig): name = 'stark' def ready(self): autodiscover_modules('stark') 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() 3 设计url 如何通过model类变量获取该模型的字符串名称和该模型所在app的字符串名称: print("===>", model._meta.model_name) print("===>", model._meta.app_label) 在ModelStark中: self.model: 用户当前访问的模型表 查看页面: 表头 表数据 search action 分页 filter 增删改(modelForm) pop 作业1: 访问任何模型时都有编辑,删除,选择 作业2: 如果用户没有配置list_display,显示对象 作业3: 名称空间
四、admin - 知识点
1.知识点1:
url()的使用:
情况1:path('book/', views.book), # book(request)
情况2:分发:
path('yuan/',yuan), # yuan
path('yuan/',([],None,None)) # None,None 代表:namespace app(name)
path('yuan/',([path('test01/',test01)],None,None)), # yuan/test01
path('yuan/',([ path('test01/',([ path('test04/',test04), # yuan/test01/test04 path('test05/',test05) # yuan/test01/test05 ],None,None)), path('test02/',test02), # yuan/test02 path('test03/',test03) # yuan/test03 ],None,None))
注: re_path(r'^test04/',test04), # 以test04开头;
re_path(r'test04/',test04), # 包含test04;
2.知识点2:
单例模式
生成单例模式的方式:
(1)使用 __new__
class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a = 1 >>> one = MyClass() >>> two = MyClass() >>> one == two True
(2)使用模块
class My_Singleton(object): x = 12 def foo(self): print(self.x) my_singleton = My_Singleton() from mysingleton import my_singleton my_singleton.foo()
3.知识点3:
admin源码:
1.注册 admin.py
from django.contrib import admin
class BookConfig(admin.ModelAdmin):
list_display = ['user', 'room']
...
admin.site.register(Book,BookConfig) # admin.site 就是 AdminSite()的一个实例化对象(单例)
admin.site.register(UserInfo,UserConfig)
admin.site.register(Room)
class AdminSite(): def __init__(self, name='admin'): self._registry = {} def register(self, model, admin_class=None): if not admin_class: admin_class = ModelAdmin self._registry[model] = admin_class(model, self) ... ... site = AdminSite()
所以:按顺序注册后,结果都在 admin.site._registry 字典里面;model为键,admin_class(model, self)为值;
即:Book为键,BookConfig()为值;
UserInfo为键,UserConfig()为值;
Room为键,ModelAdmin()为值;
注意:admin.site._registry 全局的!! 多个app共用!!(startapp02)
print(admin.site._registry) {<class 'django.contrib.auth.models.Group'>: <django.contrib.auth.admin.GroupAdmin object at 0x000002777731D400>, <class 'app01.models.Book'>: <app01.admin.BookConfig object at 0x000002777735C470>, <class 'app01.models.UserInfo'>: <app01.admin.UserConfig object at 0x000002777735C4A8>, <class 'app01.models.Room'>: <django.contrib.admin.options.ModelAdmin object at 0x000002777735C4E0>, <class 'app01.models.GF'>: <django.contrib.admin.options.ModelAdmin object at 0x000002777735C518>, <class 'app02.models.Book'>: <django.contrib.admin.options.ModelAdmin object at 0x000002777735C438>}
2.设计 url:
注意:
1.
path('yuan/',(get_urls(),None,None)),
path('yuan/',include(get_urls()))
2.
for model,admin_class_obj in admin.site._registry.items():
print('****',model) # **** <class 'app01.models.Book'>
model_name = model._meta.model_name # book
app_label = model._meta.app_label # app01
3.
temp.append(path('%s/%s/'%(app_label,model_name),(get_urls2(),None,None)))
4.
temp.append(path('add/',add))
temp.append(re_path(r'(\d+)/delete/',delete))
temp.append(re_path(r'(\d+)/change/',change))
temp.append(re_path(r'^$',list_view))
5.
# 24条 url 。。。
# http://127.0.0.1:8020/yuan/app01/book/
# http://127.0.0.1:8020/yuan/app01/userinfo/add/
# http://127.0.0.1:8020/yuan/app01/book/5/delete/
# http://127.0.0.1:8020/yuan/app02/book/
。。。
。。。
def add(request): return HttpResponse('add') def delete(request,del_id): return HttpResponse('delete') def change(request,change_id): return HttpResponse('change') def list_view(request): return HttpResponse('list_view') def get_urls2(): temp = [] temp.append(path('add/',add)) temp.append(re_path(r'(\d+)/delete/',delete)) temp.append(re_path(r'(\d+)/change/',change)) temp.append(re_path(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) # **** <class 'django.contrib.auth.models.Group'> # **** <class 'app01.models.Book'> # ... ... # **** <class 'app02.models.Book'> model_name = model._meta.model_name # book app_label = model._meta.app_label # app01 temp.append(path('%s/%s/'%(app_label,model_name),(get_urls2(),None,None))) # http://127.0.0.1:8020/yuan/app01/book/ # http://127.0.0.1:8020/yuan/app01/book/add/ # ... ... # http://127.0.0.1:8020/yuan/app02/book/ # 24条 url 。。。 return temp urlpatterns = [ path('admin/', admin.site.urls), path('yuan/',(get_urls(),None,None)), # path('yuan/',include(get_urls())) ]
from django.contrib import admin from django.urls import path,re_path,include from app01 import views from django.shortcuts import HttpResponse def yuan(request): return HttpResponse('yuan') def test01(request): return HttpResponse('test01') def test02(request): return HttpResponse('test02') def test03(request): return HttpResponse('test03') def test04(request): return HttpResponse('test04') def test05(request): return HttpResponse('test05') def add(request): return HttpResponse('add') def delete(request,del_id): return HttpResponse('delete') def change(request,change_id): return HttpResponse('change') def list_view(request): return HttpResponse('list_view') def get_urls2(): temp = [] temp.append(path('add/',add)) temp.append(re_path(r'(\d+)/delete/',delete)) temp.append(re_path(r'(\d+)/change/',change)) temp.append(re_path(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) """ **** <class 'django.contrib.auth.models.Group'> **** <class 'app01.models.Book'> **** <class 'app01.models.UserInfo'> **** <class 'app01.models.Room'> **** <class 'app01.models.GF'> **** <class 'app02.models.Book'> """ model_name = model._meta.model_name # book app_label = model._meta.app_label # app01 temp.append(path('%s/%s/'%(app_label,model_name),(get_urls2(),None,None))) # yuan/app01/book/ # http://127.0.0.1:8020/yuan/app01/book/ # http://127.0.0.1:8020/yuan/app01/book/add/ # http://127.0.0.1:8020/yuan/app01/userinfo/add/ # http://127.0.0.1:8020/yuan/app01/book/5/delete/ # http://127.0.0.1:8020/yuan/app01/userinfo/4/delete/ # http://127.0.0.1:8020/yuan/app01/book/5/change/ # http://127.0.0.1:8020/yuan/app02/book/ # 24条 条 url 。。。 return temp # get_urls() urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), path('index/', views.index), path('book/', views.book), # path('yuan/',yuan), # path('yuan/',([path('test01/',test01)],None,None)), # # path('yuan/',([ # path('test01/',([ # path('test04/',test04), # path('test05/',test05) # ],None,None)), # path('test02/',test02), # path('test03/',test03) # ],None,None)) # path('yuan/',([ # path('test01/',([ # re_path(r'^test04/',test04), # # http://127.0.0.1:8000/yuan/test01/test04/ # # re_path(r'test04/',test04), # http://127.0.0.1:8000/yuan/test01/abc/test04/ 这样也可以,只要后面包含test04 # path('test05/',test05), # http://127.0.0.1:8000/yuan/test01/test05/ # ],None,None)), # http://127.0.0.1:8000/yuan/test01/ # path('test02/',test02), # http://127.0.0.1:8000/yuan/test02/ # path('test03/',test03), # http://127.0.0.1:8000/yuan/test03/ # ],None,None)), # None,None namespace app 是两个名字!! path('yuan/',(get_urls(),None,None)), # path('yuan/',include(get_urls())) ]