1. 程式人生 > 實用技巧 >django url反向解析

django url反向解析

引子:

  天冷,依舊是複習

程式碼:

  html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<h1>這是在HTML頁面把url寫死</h1>

<a href="/index/">首頁</a>

<h1>這是在html頁面把利用反向解析url的結局args  url 後跟的 是別名</h1>
<a href="{% url 'index' 'house' %}">反向解析</a>

<h1>這是在html頁面把利用反向解析url的結局kwargs url 後跟的 是別名</h1>
<a href="{% url 'home' 'yuanbao' %}">反向解析</a>
<script>
</script>
</body>
</html>

  view

def test(request):
    """
    反向解析
    :param request:
    :return:
    """
    #實際反向解析就是調取了 reverse
    # from django.urls import reverse
    # # 實際上就會 到url  根據reverse 中的引數 依次匹配
    # a = reverse("index", args=("house",))
    # print("首頁url是:===>{}",a)
    #
    # b=reverse("home",kwargs={"name":"yuanbao"})
    # print("kwargs===> url===>{}".format(b))
    return render(request,"test.html")

  urls

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

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^delete/表名/id值/') 匹配到的值 直接傳給 檢視函式
    url(r'^delete/([a-zA-z]+)/(\d+)/',views.delete),
    # 預設返回首頁
    url(r'^$',views.home),
    # url 的反射
    url(r'^index/([a-zA-z]+)/$',views.index,name="index"),
    url(r'^index/(?P<name>[a-zA-z]+)/$',views.index,name="home"),
    url(r'^res666/$',views.res,name="res"),
    url(r'^test/$',views.test,name="test"),

]

  我一般不再url上拼接引數,麻煩,採用分層路由是不錯的選擇

manage.py同級的一級路由

from django.conf.urls import url,include
from django.contrib import admin
#from app01 import views as ap
from app01 import urls as ap01

urlpatterns = [
    url(r'^admin/', admin.site.urls),
url(r'^ord/', include(ap01)),

]

  app下的2級路由

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


urlpatterns=[

url(r'^create_channel_item/', ap.create_channel_item),
url(r'^create_ord/', ap.create_ord),
url(r'^create_rma_ord/', ap.create_rma_ord),
url(r'^insert_ord_channel/', ap.insert_ord_channel),
url(r'^insert_dis_cen/', ap.insert_dis_cen),
url(r'^create_source_order/', ap.create_source_order),
url(r'^create_source_rma_order/', ap.create_source_rma_order),
url(r'^create_ventory_ins/', ap.create_ven_ins),
url(r'^create_ven_ins_finsh/', ap.create_ven_ins_finsh),
url(r'^create_ord_info/', ap.create_ord_info),
url(r'^create_print_shipping_ord/', ap.create_print_shipping_ord),
url(r'^create_ship_disconnect/', ap.create_ship_disconnect),
url(r'^create_combina_item/', ap.create_combina_item),
url(r'^crest_submit_item_app/', ap.crest_submit_item_app),
url(r'^create_source_com_ord/', ap.create_source_com_ord),

]