xadmin系列之django的url分发的方式
一、先介绍一下我们自己的urls中是如何进行路由分发的
一、一级路由
urlpatterns = [
url(r'^upload/', views.upload,name="upload"),
url(r'^article-site/(?P<auther>\w+)', views.article_site,name="article"),
url(r'^login/', views.login,name="bbs_login"),
url(r'^index/', views.index,name="bbs_index"),
url(r'^register/', views.register,name="bbs_register"),
url(r'^logout/', views.logout, name="bbs_logout"),
url(r'^up_down/', views.up_down,name="up_down"),
url(r'^add_comment/', views.add_comment,name="add_comment"),
url(r'^comment_tree/(?P<nid>\d+)', views.comment_tree,name="comment_tree"),
url(r'^(?P<name>\w+)/$', views.blog,name="bbs_blog"),
url(r'^(?P<name>\w+)/(?P<tid>\d+)/$', views.article), ]
二、二级路由
from django.conf.urls import include
url(r'^app1/',include("app1.urls")),
三、路由分发,这里还可以里面在嵌套一层
url(r'^cui/', (
[url(r'^test1/', test.test1),
url(r'^test2/', test.test2),
url(r'^test3/', test.test3),
]
,None,None)),
二、下面看下django的admin是如何进行路由分发的
django的admin就是用上面的第三种方式实现urls的分发
先掌握一个知识点
a、通过表的对象去获取表的名称,这里需要注意,获取到的表名是全小写的
from app1.models import Article
Article._meta.model_name
'article'
b、通过表的对象获取该表所属的app的名称
Article._meta.app_label
'app1'
下面我们用路由分发的方式进行分发,我们要一个类似这样的url
cui/app的名称/表的名称/add/ -------增加
cui/app的名称/表的名称/list/ --------查看
cui/app的名称/表的名称/1/change----编辑
cui/app的名称/表的名称/1/del-----删除

下面看下我们定义的函数geturls函数,这个函数的主要的目的就是获取表的名称和表所属的app的名称
def geturls():
temp = []
for model,admin_class in admin.site._registry.items():
# 通过表的对象获取表的名称
model_name = model._meta.model_name # 通过表的对象获取表的app的名称
app_name = model._meta.app_label temp.append(
url(r'^{app_name}/{model_name}/'.format(app_name=app_name,model_name=model_name), (geturlsoperation(),None,None))
)
return temp
这里我们为上面用到的admin.site._registry这个函数呢?我们看下源码
在admin.site文件中最后返回了一个对象,我们导入admin.site就相当于导入了一个AdminSite的对象,而这个对象和我们前面学的非常的相似,他就是一个单实例的对象

我们看下AdminSite这个类的
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
""" # Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin') # Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration') # Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration') # URL for the "View site" link at the top of each admin page.
site_url = '/' _empty_value_display = '-' login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None def __init__(self, name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
all_sites.add(self)
这里我们可以看到_registry是一个字典,我们在看下AdminSite这个类的register这个函数是如何使用这个变量的
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class. If a model is already registered, this will raise AlreadyRegistered. If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured(
'The model %s is abstract, so it cannot be registered with admin.' % model.__name__
) if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__) # Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options) # Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
这里就是一个字典,字典的k表的对象,v是这个表的对象对应的admin_class,admin_class其实就是我们注册的时候的类
class ad(admin.ModelAdmin):
def manyTomany(self):
return mark_safe("<a>删除</a>")
list_display = ["content","article",manyTomany]
# 控制admin显示某张标签的那些字段
# 这里我们还可以自定义一个字段,函数名就是字段的名称,函数的值就是字段的返回值
list_editable = ["article"]
# 定义那些字段可以在编辑,可以表的页面直接编辑
list_display_links = ["content","article"]
# 控制那些字段可以点击进入某张表的详情
admin.site.register(models.ArticleDetail,ad)
就是我们这个ad

我们在看下geturlsoperation这个函数,他就是返回我们的增删改查的
def geturlsoperation():
temp = []
temp.append(
url(r'^$',test.list_view)
)
temp.append(
url(r'^add/$',test.add_view)
)
temp.append(
url(r'^(?P<cid>\d+)/change/$',test.change_view)
)
temp.append(
url(r'^(?P<did>\d+)/del/$',test.del_view)
)
return temp
xadmin系列之django的url分发的方式的更多相关文章
- django的url分发封装
h2, body>h3, body>h4, body>h1{ padding: 10px; background-color: #4cae4c; text-align: center ...
- Django学习之十一:真正理解Django的路由分发和反解url原理
目录 URL Dispatcher 简介 模式概念 对比URLPattern 与 URLResolver (多态的体现) 构建子路由几种方式 反解url算法逻辑 URL Dispatcher 简介 d ...
- django url分发,视图,模板回顾
Django基础轮廓 MTV+controller 一 url分发系统: 1 简单使用 url(r'^articles/2003/$', views.special_case_2003), # spe ...
- Django url分发到工程里
因为我们建立了Django后 ,url是在mysite下的全局对象 因为我们实际项目里不可能只有一个工程 而全放在全局里去分发url 会让代码耦合度提高,代码量大后会造成维护困难.这时候我们把url分 ...
- Django路由配置之子路由include(URL分发)
子路由include(URL分发) 在一个项目中可能存在多个应用,为了方便区分和管理,在项目的总路由urls.py中会进行路由分发: (1)项目总路由导入from django.conf.urls ...
- day53:django:URL别名/反向解析&URL分发&命名空间&ORM多表操作修改/查询
目录 1.URL别名&反向解析 2.URL分发&命名空间 3.ORM多表操作-修改 4.ORM多表操作-查询 4.1 基于对象的跨表查询 4.2 基于双下划线的跨表查询 4.3 聚合查 ...
- day 82 URL分发
一 .admin 流程 (1) 启动 autodiscover_modules('admin', register_to=site) (2) 注册 单例模式 admin.site=AdminSite( ...
- Django的URL调度
1.URLconf (URL configuration):(Django版本1.11.20,其它版本可能各有差异.) 在Django中Python后端与前端URL进行交互,是通过一个名为urlcon ...
- Django的URL路由系统
一. URL配置 URL配置就像Django所支撑网站的目录.它的本质是URL与要为该URL调用的视图之间的映射表.你就是以这种方式告诉Django,对于哪个URL调用的这段代码. 基本格式 from ...
随机推荐
- Leetcode 题解 First Missing Positive
Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0] ...
- 初识AutoMapper
在开始本篇文章之前,先来思考一个问题:一个项目分多层架构,如显示层.业务逻辑层.服务层.数据访问层.层与层访问需要数据载体,也就是类.如果多层通用一个类,一则会暴露出每层的字段,二者会使类字段很多,而 ...
- 发现一个好办法-有问题可以到UNITY论坛搜索
特别专业的问题,较新技术,可以到UNITY论坛搜索或发问,那里,或许会有UNITY的官方技术支持回答 https://forum.unity.com/threads/remote-deep-profi ...
- Tomcat 7集群基于redis的session共享设置
经过测试之后,发现是tomcat中redis相关jar包问题,替换jar包后A产品运行正常. tomcat/lib目录下将commons-pool2-2.1.jar.jedis-2.1.0.jar.t ...
- Arcgis map export or print Error: Cannot map metafile into memory. Not enough memory
Arcgis map export or print Error: Cannot map metafile into memory. Not enough memory Link: https:/ ...
- 单例模式 demo
// 用单例模式实现自定义颜色类 public class MyColor { private static MyColor _redColor = null; public static MyCol ...
- hadoop-2.7.3完全分布式部署
一.环境介绍 IP host JDK linux版本 hadop版本 192.168.0.1 master 1.8.0_111 centos7.2.1511 hadoop-2.7 ...
- .gitignore设置
git提交的时候一直提示 e/.idea/workspace.xml文件冲突, 这个文件是IDE编辑的时候自动带的文件,这个文件在提交的时候是不需要上传到git中的 这个时候我们需要这种.gitign ...
- import模块
一.在import模块的时候发生的事情 1.寻找模块2.如果找到了,就开辟一块空间,执行这个模块3.把这个模块中用到的名字都录到新开辟的空间中4.创建一个变量来引用这个模块中 二.注意事项: *1.模 ...
- 基于WebQQ3.0协议写一个QQ机器人
最近公司需要做个qq机器人获取qq好友列表,并且能够自动向选定的qq好友定时发送消息.没有头绪,硬着头皮上 甘甜的心情瞬间变得苦涩了 哇 多捞吆 1.WEBQQ3.0登陆协议 进入WEBQQ, htt ...