zoukankan      html  css  js  c++  java
  • Django路由系统---url无命名分组

    django重点之url无命名分组[参数有顺序要求]

    settigs.py:增加STATICFILES_DIRS静态资源路径配置,名称为创建的文件夹名称

    'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 设置templates的路径为Django以前版本
    # 'DIRS': [],      # 注释掉该行,此为Django 2.0.1最新版本
    # 'django.middleware.csrf.CsrfViewMiddleware',
             ...省略默认配置
    STATIC_URL = '/static/'
    TEMPLATE_DIRS = (os.path.join(BASE_DIR,  'templates'),)  # 原配置
    # 静态资源文件
    STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 现添加的配置,这里是元组,注意逗号

    templates/func.html/ func1.html/ func2.html

    <!DOCTYPE html>
    <html lang="en">
    <head> <meta charset="UTF-8"></head>
    <body>
        <!-- func.html -->
        <p id="h1">无命名分组[参数无顺序要求]</p>
        <!-- func1.html -->
        <h1 id="h1" style="color:red">无命名分组[参数无顺序要求]<br> 
            返回正则匹配结果是:{{ year }}年
        </h1>
        <!-- func2.html -->
        <h1 id="h1" style="color:red">无命名分组[参数无顺序要求]<br> 
            返回正则匹配结果是:{{ year }}年{{ month }}月
        </h1>
    </body>
    </html>

    mysite2/urls.py

    from django.contrib import admin
    from django.urls import path
    from blog import views
    from django.conf.urls import url
    urlpatterns = [
    # 正则需要配合URL函数来进行,path在测试中无法匹配正则
    # url(r'^year', views.func),  # 绝对路径匹配
    url('^year/[0-9]{4}/$', views.func),  # 正则表达式匹配
    url(r'^only_year/([0-9]{4})/$', views.func1),  # 用小括号括起来的的匹配,可以无名传值给函数    url(r'^year_month/([0-9]{4})/([0-9]{2})/$', views.func2), # 用2个括号括起来,可以2个传值给函数
    ]

    views.py

    from django.shortcuts import render, HttpResponse
    import datetime
    
    # 绝对值匹配/正则匹配
    def func(request):
        return render(request, "func.html")
    
    # 无命名匹配,返回一个参数
    def func1(request, year):
        return render(request, "func1.html", {"year": year})
    
    # 无命名匹配,返回2个参数
    # def func2(request, year, month):
    def func2(request, month,year):  # 无顺序要求,可以更换位置
        # 此时的month代表第一个括号内的参数,year代表第二个括号内参数
        return render(request, "func2.html", {"year": year, "month": month}) 

    页面显示:

    image_thumb

    更换传递给函数参数位置后的结果显示:

    image_thumb[1]

  • 相关阅读:
    各种工具网站汇总
    Python中numpy库unique函数解析
    matlab中集合运算函数——解析
    hash算法搜索获得api函数地址的实现,"kernel32.dll", "CreateThread"
    PEB及LDR链
    PE文件结构及其加载机制
    spring boot2.0一看就会的超详细快速入门(七)-访问静态资源
    spring boot2.0一看就会的超详细快速入门(六)-集成Thymeleaf模板引擎
    spring boot2.0一看就会的超详细快速入门(五)-开发人员工具devtools
    spring boot2.0一看就会的超详细快速入门(四)-自动配置原理
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9398155.html
Copyright © 2011-2022 走看看