Django 路由reverse配置

  1. 如果没有使用reverse()之前的路由,只要在urls.py修改了匹配的pattern,那么很多地方调用了该url的代码都要修改,可谓是牵一发而动全身。
    reverse()就是用来改善这种情况的。

 

2.Django配置
a.配置django工程:

django-admin startproject send_mail_prj
cd send_mail_prj
django-admin startapp app01

 

b.在项目的settings.py注册app01

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',  # 建议使用该方式注册,当然也可以直接是'app01'
]

 

c.在应用里创建urls.py文件

from django.conf.urls import url
from . import  views

# 定义该app_name变量为应用名字
app_name = 'app01'
urlpatterns = [
    url(r'register/$', views.register, name='register'),
    url(r'index/$', views.register, name='index'),                  # name是别名
    url(r'tiaozhuan/$', views.tiaozhuan, name='tiaozhuan')
]

 

d.在项目的urls.py文件中,include应用的url

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
    path('admin/', admin.site.urls),
    # 导入app.urls时 加入namespace是为了防止其他app.urls里面的name重复了
    # 后续reverse获取url时,通过reverse('namespace:name')
    url(r'^', include('app01.urls', namespace='app01')),
]

 

e.在应用视图中通过reverse()的方式来获取路由:

from django.shortcuts import render, redirect
from django.http import HttpRequest, HttpResponse
from celery_tasks.sms.tasks import sendEmail

from django.urls import  reverse

def register(request):
    # 发送邮件
    sendEmail.delay()
    return HttpResponse('hello')

def tiaozhuan(request):
    # app01是名称空间;
     # index 是在urls.py 里面的别名 url(r'index/$', views.register, name='index'),
    path = reverse('app01:index')
    print(path)
    return redirect(path)

 

3.访问页面,测试实验
a.浏览器访问http://127.0.0.1/tiaozhuan 会跳转到http://127.0.0.1/index/
Django 路由reverse配置

 

b.修改应用urls.py的路由patterns

from django.conf.urls import url
from . import  views

app_name = 'app01'
urlpatterns = [
    url(r'register/$', views.register, name='register'),
    url(r'home/$', views.register, name='index'),   # 修改为home
    url(r'tiaozhuan/$', views.tiaozhuan, name='tiaozhuan')
]

 

c.继续浏览器测试
浏览器访问http://127.0.0.1/tiaozhuan 会跳转至 http://127.0.0.1/home/
Django 路由reverse配置
Django 路由reverse配置

 

结论:
测试完成,即使路由的匹配模式修改了,也不影响通过reverse()调用的URL

上一篇:数组


下一篇:UVA11610 Reverse Prime