1. 程式人生 > >Django的url路由系統簡介

Django的url路由系統簡介

創建項目 att onf lan from include title 括號 list

1.創建項目時的初始化值

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

urlpatterns = [
    url(r^admin/, admin.site.urls),
]

2.創建多個app時可以使用include()函數完成分流

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include

urlpatterns = [
    url(r^admin/
, admin.site.urls), url(r^app01/, include("app01.urls")), url(r^app02/, include("app02.urls")), ]

3.引入視圖函數完成url與函數的對應關系

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


urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^index/, views.index),
]

4.給url取一個別名

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


urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^index/, views.index, name=別名),
]

5.正則匹配url和偽靜態結合

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views urlpatterns = [ url(r^admin/, admin.site.urls), url(r^index/(\w+).html$, views.index), ]

6.重點介紹一下Django裏面url別名

"""url別名是Django才有的特性,通用標準還是在後端生成url再傳遞給html"""
from django.shortcuts import render, HttpResponse
from django.urls import reverse


def index(request):
    """
    可以通過reverse反向查詢url,在數據庫層面則根據不同用戶權限存儲url別名
    :param request:
    :return:
    """
    # 1.在這裏可以直接查詢數據庫獲取url別名,然後傳入render()
    url_list = [
        url_one,url_two,url_three
    ]
    # 2.url = reverse("url_one")  # 也可以通過別名直接反向獲取url然後傳入render()
    return render(request, index.html, {url_list: url_list})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>菜單</h1>
    {% for i in user_list %}
        <a href="">c1</a>
    {% endfor %}
    <ul>
        {% for i in url_list %}
            {# 這裏傳入url直接放在雙花括號中 #}
            <li>{{ i.id }} | <a href="{{ i }}">編輯</a></li>
            {# 如果是別名則是花括號加百分號和url反向生成url #}
            <li>{{ i.id }} | <a href="{% url i %}">編輯</a></li>
        {% endfor %}
    </ul>
</body>
</html>

Django的url路由系統簡介