• 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
    

      

  • 相关阅读:
    Android框架: MVC MVP MVVM
    Apache Tomcat -8.0.45
    【MySQL】Database connections will be migrated
    MySQL(mysql-installer-community-5.7.18.1 Windows10)
    代码版本控制(Source Control)
    HTML 5
    微信小程序
    Android Studio 2.3.3 安装
    React Native
    2018面向对象程序设计(Java)第12周学习指导及要求
  • 原文地址:https://www.cnblogs.com/bainianminguo/p/9932784.html
Copyright © 2020-2023  润新知