Django路由系统---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_named.html

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"></head>
<body>
    <h1 id="h1" style="color:red">命名分组[参数无顺序要求]<br>
        返回正则匹配结果是:{{ named_year }}年 {{ named_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
# 正则需要配合URL函数来进行,path在测试中无法匹配正则
  url(r'^year_month_named/(?P<named_year>[0-9]{4})/(?P<named_month>[0-9]{2})/$', views.func_named)

views.py

from django.shortcuts import render, HttpResponse
import datetime 
# 命名匹配,匹配2个参数
# def func_named(request, named_month, named_year): # 更换参数的位置,不影响数据内容
def func_named(request, named_year, named_month):  
    return render(request, "func_named.html", {"named_year": named_year, "named_month": named_month})

页面显示:

image_thumb[2]_thumb

猜你喜欢

转载自www.cnblogs.com/ftl1012/p/9398157.html