Django的url路由系统简介

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和伪静态结合生成动态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})

 


"en">

    "UTF-8">
    


    

菜单

{ % for i in user_list %} "">c1 { % endfor %}
    { % for i in url_list %} { # 这里传入url直接放在双花括号中 #}
  • { { i.id }} | "{ { i }}">编辑
  • { # 如果是别名则是花括号加百分号和url反向生成url #}
  • { { i.id }} | "{% url i %}">编辑
  • { % endfor %}

 

转载于:https://www.cnblogs.com/Guishuzhe/p/10385191.html

你可能感兴趣的:(python,数据库,后端)