简介
使用index和login视图举例详解了django框架路由系统的6种常用场景。
views.py
# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom django.http import HttpResponsedef index(request):return HttpResponse("<h1>index</h1>")def login(request,userName,passWord):if passWord == 'test1234_':return HttpResponse("%s,欢迎登录!" %(userName))else:return HttpResponse('用户名和密码错误')
urls.py
1. 直接导入views.py中的方法名
from web.views import index,loginurlpatterns = [url(r'^index/$',index),]
2. 不直接导入方法名,而是只导入views.
3. 使用正则中的分组方法进行参数传递,不指定参数名,按传入顺序 接收。from web import viewsurlpatterns = [url(r'^index/$', views.index),]
from web import views
urlpatterns = [
url(r'^index/$', views.index),
url(r'^login/(w+)/(w+)$', views.login),
]
输入正确时:输入错误时:
4. 使用正则中的分组方法进行参数传递,指定要给那个参数传值
from web import viewsurlpatterns = [url(r'^index/$',views.index),url(r'^login/(?P<passWord>w+)/(?P<userName>w+)$',views.login),]
5. 固定参数(passWord 属性为固定参数,即使你传入正确的密码“test1234_”,也会显示用户名和密码错误,因为login方法实际接收到的值固定为“test1234”)输入正确时:输入错误时:
urlpatterns = [url(r'^index/$', views.index),url(r'^login/(?P<userName>w+)', views.login, {'passWord':'test1234'}),]
6. 根据app对路由规则进行分类
1) mysite.urls.py
from django.conf.urls import url,include
urlpatterns = [url('^web/',include('web.urls')),]
2) mysite.web.urls.py
from django.conf.urls import url
from web import views
urlpatterns = [
url('^index/$', views.index),url('^login/(?P<userName>w+)/(?P<passWord>w+)$', views.login),]
附录1:django 常用URL配置方法
附录二:Django URL Name详解
http://code.ziqiangxuetang.com/django/django-url-name.html