Django路由系统---url无命名分组
2023-09-11 14:20:11 时间
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})
页面显示:
更换传递给函数参数位置后的结果显示:
相关文章
- Django组件:django-simple-captcha 使用
- Django之url路由
- Django获取内网ip
- django-admin 动态增加路由
- 第三百七十节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)用Django实现搜索结果分页
- 第三百一十五节,Django框架,CSRF跨站请求伪造
- Django根据现有数据库建立/更新model
- 【秒懂】号称最为简明实用的Django上手教程(下)
- Python的Django框架中的URL配置与松耦合
- django框架进阶-中间件-长期维护
- [Django] Auth django app with rest api
- [Django] Start a new django project
- Python Django 获取多条记录API
- Python Django 文件上传代码示例
- 14 - vulhub - Django debug page XSS漏洞(CVE-2017-12794)
- Python编程:几个基于Django的CMS内容管理系统
- Django 之 URL(路由)分发机制
- Django===django工作流
- django settings最佳配置
- Django之django-redis对数据进行简单缓存