Django --- routing system, URLconf configuration instructions (position parameter) regular expressions, grouping named (capture key parameters), pass extra arguments to the view, named reverse lookup url and the url, url namespace

Django --- routing system, URLconf configuration instructions (position parameter) regular expressions, grouping named (capture key parameters), pass extra arguments to the view, named reverse lookup url and the url, url namespace

Dian a URLconf configuration

      URL support configuration is a directory site, essentially a mapping table between the URL and view the URL function call

urlconf format

from django.conf.urls import url

urlpatterns = [
     # url() 是包含 请求的url和视图的对应关系的函数
     # def url(regex, view, kwargs=None, name=None):
     url(正则表达式, views视图,参数,别名),
]
    
    
### 参数解释:
    # 正则表达式 : 一个正则表达式字符串
    # views视图: 一个可以调用的对象(最终执行的还是view函数), 或者是一个函数
    # kwargs参数: 需要传给视图的参数.以字典形式传递
    # name 别名 : 给当前的函数起一个名字, 用于做反向解析
    

    
    
    
### 示例如  Django的版本1.X
from django.conf.urls import url
from . import views
# urlpatterns 是存放这些对应关系表
urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]




### 注意 在Django2.X版本
    # re_path 和 url 具有相同的用法,正则路径
from django.urls import path,re_path
urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]

   Django's description urlpatterns

Dian two regular expressions

# 示例:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003), 
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]


# 正则符号简单说明:
    ^XX 以XX开头
    $XX 以XX结尾
    () 分组
    + 匹配1个或多个
    \ 下一个字符标记为一个特殊字符、或一个原义字符、或一个向后引用、或一个八进制转义符。
    \d+ 匹配一个或多个数字
    \w+ 匹配数字字母下划线
    [0-9] 0-9数字任意一个
    [0-9a-zA-z] #大小写字母数字,任意一个.
    {3} # 3个
    {0,4} # 范围 0-4个
    

Explanation

# 1. urlpatterns中的元素按照书写顺序从上往下逐一匹配正则表达式,一旦匹配成功则不再继续。

# 2.若是从url捕获一个值,只需要在其周围放置一个() ,表示分组. 如:'(\w+)/(\d+)',分了两个组,意味着在视图函数中需要接受两个参数

# 3.不需要在url前添加前导的反斜杠,每个url都有,有Django自动添加.例:是'^XXX'这样,而不是'^/xxx'这样

# 4.每个正则表达式前面的'r' 是可选的但是建议加上。  r表示不转义

# ps:
    分组之后,参数传递是按照位置参数去传递
    def xxx(request,x1,x2):  # x1和x2的位置不能变,接收参数的顺序位置不能乱
#### 补充:
# 是否开启URL访问地址后面不为/跳转至带有/的路径的配置项
    APPEND_SLASH=True
# Django settings.py配置文件中默认没有 APPEND_SLASH 这个参数,但 Django 默认这个参数为 APPEND_SLASH = True。 其作用就是自动在网址结尾加'/'。

from django.conf.urls import url
from app01 import views

urlpatterns = [
    url(r'^blog/$', views.blog),
]

# 访问 http://www.example.com/blog 时,默认将网址自动转换为 http://www.example/com/blog/ 。

# 如果在settings.py中设置了 APPEND_SLASH=False,此时我们再请求 http://www.example.com/blog 时就会提示找不到页面。

Wed and group name match

分组命名正则表达式组的语法: (?P<name>pattern)
    # name是组的名称,
    # pattern是要匹配的模式。

Packet name

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]


# 说明: 命名分组的捕获的参数是关键字参数. 
    def XXX(request,year,month,day)     # 作为关键字参数传递 ,year=XXXX,month=YY,顺序位置任意

URLconf matching position

URLconf look at the URL request, it will be treated as a normal Python string. It does not include GET and POST parameters, and domain name.

例如,http://www.example.com/myapp/ 请求中,URLconf 将查找 /myapp/ 。

在http://www.example.com/myapp/?page=3 请求中,URLconf 仍将查找 /myapp/ 。

URLconf 不检查请求的方法。换句话讲,所有的请求方法 —— 同一个URL的`POST`、`GET`、`HEAD`等等 —— 都将路由到相同的函数。

Capture parameters are always strings

Each captured in the URLconf parameters as a normal Python string passed to view, regardless of regular expressions to match what way. For example, in the following line URLconf:

url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),  # year 参数 始终是一个字符串

The default value specified in the function view

# urls.py中
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^blog/$', views.page),
    url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
]

# views.py中,可以为num指定默认值. 接收num不存在时,使用默认值
def page(request, num="1"):  
    pass

include other URLconfs

#At any point, your urlpatterns can “include” other URLconf modules. This
#essentially “roots” a set of URLs below other ones.

#For example, here’s an excerpt of the URLconf for the Django website itself.
#It includes a number of other URLconfs:


from django.conf.urls import include, url

urlpatterns = [
    
    # 路由分发  include 包含 app01下的url.py的所有的  请求和函数对应关系
    # namspace 表示: app01的名称空间 使用时'app01:XXX'
    # url函数:url(regex, view, kwargs=None, name=None):
    url(r'^app01/', include('app01.urls',namespace='app01')), # 可以包含其他的URLconfs文件
]

Dian four additional parameters passed to the view function

      That is: a view from the function argument passing keyword url

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),
]



#对于请求:/blog/2019/
Django 将调用views.year_archive(request, year='2019', foo='bar')。
当传递额外参数的字典中的参数和URL中捕获值的命名关键字参数同名时,函数调用时将使用的是字典中的参数,而不是URL中捕获的参数。 # 即是 后面的更新替换 前面的值.

Five named Dian reverse lookup url and the url

      A common requirement is to get the final form of the URL for the embedded into the generated content (and views displayed to a user's URL, etc.) or for navigation processing server (redirection).

      Type (positional parameters, keyword parameters) and other information necessary to obtain the value of a URL beginning think the information is processed identification (such as name) its view, have to find the correct URL parameters of view.
Django provides a way is to let the URL mapping URL design is the only place. You fill your URLconf, then use it in both directions:

1. According to URL request user / browser launched, it calls the correct Django view, and extract the value of its required parameters from the URL.

The view identifier Django and its value will be passed to the parameter, the associated URL.

# 在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.在模板中:使用url模板标签。
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.在Python 代码中:使用django.core.urlresolvers.reverse() 函数
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3.在更高层的与处理Django 模型实例相关的代码中:使用get_absolute_url() 方法。
        
# PS: 解析url时,或者反向解析url时.都得到一个完整的路径        

For 'Li' child:

url(r'^home', views.home, name='home'),  # 给我的url匹配模式起名为 home
url(r'^index/(\d*)', views.index, name='index'),  # 给我的url匹配模式起名为index

# 模板页面
    语法:{% url '别名' %} ,如{% url 'home' 参数1 参数2 %}

# view视图函数
    语法:
         from django.urls import reverse
        reverse('别名', args=("2018", ))# args 是接收一个元组参数,反向生成url时传递的位置参数.
        
       
### urls.py
urlpatterns = [
    # 一个位置参数 
    url(r'^publish_edit/(\d+)',views.PublishEdit.as_view(),name='publish_edit'),
    
    # 一个位置参数,一个关键字参数
    url(r'^(\w+)_del/(?P<pk>\d+)/$', views.delete, name='delete'),

]

### views.py 视图函数
    # cbv 接收参数
    class PublishEdit(View):

        def get(self, request,pk):
            ret = models.Publisher.objects.filter(pk=pk).first()
                ....
            return render(request, 'publish_edit.html', res)

        def post(self, request,pk):
            ret = models.Publisher.objects.filter(pk=pk).first()
                .....
           return redirect(reverse('app01:publisher')) # 反向解析 'app01/publisher/' 得到一个完整的路径

    #fbv 接收参数 table, pk    
    def delete(request,table,pk):
        tab=getattr(models,table.capitalize()) # 通过反射去获取models的类名
        obj = tab.objects.filter(pk=pk).first()
        if not obj:
            return HttpResponse('醒醒,删啥呢~~')
        obj.delete()

        # 由于使用了 namespace 所以要 拼接反向解析的url : reverse('app01:'+table+'') ,
        return redirect(reverse('app01:'+table+'')) #反向解析
    

### 页面模板
    # 使用模板标签语法: url 别名(注意名称空间) 参数1 参数 2   
    <a href="{% url 'app01:publish_edit' publish.pk  %}">编辑</a>
    
    # 使用模板标签语法: url 别名(注意名称空间) 参数1  
    <a href="{% url 'app01:delete' 'publisher' publish.pk %}">删除</a>

Note:

   To complete the example above URL reverse lookup, you will need to use named URL patterns. String name used in the URL can contain any characters you like. Not only restricted to valid Python names.

   When naming your URL patterns, make sure that the name does not use the name conflicts with other applications. If your URL pattern is called comment, and the other applications have a similar name, when you use this name in the template can not guarantee what will insert URL.

   Add a prefix in the URL name, such as the name of the application, it will reduce the possibility of conflict. We recommend myapp-commentinstead comment.

Six Dian namespace

Even if the same APP use a different URL name, the URL namespace mode also allows you to reverse the only named URL.

Requirements ps:

1. In the beginning the preparation of project, write the name space.

2. Write the name of the space is more than easy to develop. There may be a function of the same name. In order to distinguish, so the only use of the name space

from django.conf.urls import url, include
 
urlpatterns = [
    url(r'^app01/', include('app01.urls', namespace='app01')),
    url(r'^app02/', include('app02.urls', namespace='app02')),
]



# app01 的 urls.py
    from django.conf.urls import url
    from app01 import views

    app_name = 'app01'
    urlpatterns = [
        url(r'^(?P<pk>\d+)/$', views.detail, name='detail')
    ]
    
# app02 的 urls.py
    from django.conf.urls import url
    from app02 import views

    app_name = 'app02'
    urlpatterns = [
        url(r'^(?P<pk>\d+)/$', views.detail, name='detail')
    ]
    
 ### PS:现在,我的两个app中 url名称重复了,我反转URL的时候就可以通过命名空间的名称得到我当前的URL。

Namespace syntax:

# 模版中使用
    {% url 'app01:detail' pk=12 pp=99 %}
    {% url 'app02:detail' pk=11 p2=99 %}
    
# views函数中使用
    v1 = reverse('app01:detail', kwargs={'pk':11})
    v2 = reverse('app02:detail', kwargs={'pk':11}) # 

Guess you like

Origin www.cnblogs.com/dengl/p/11462398.html