Django学习(url配置及参数获取)
Django 如何处理一个请求
当用户通过浏览器发送一个请求给Django网站时,Django执行过程:
1.Django首先在配置文件setting.py中找到 :ROOT_URLCONF = 'test2.urls' 作为根模块
2.加载模块,执行项目包下面的urls.py 文件中的urlpatterns
3.执行应用包下面的urls.py文件中的urlpatterns
4.遍历整个列表,通过正则表达式会找到基于view的函数或者类
5.如果没有匹配到,则会自动调用Django的错误页面
项目开发中配置url
1.在根目录下的urls文件配置include 引入应用 stu下的urls
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^student/',include('stu.urls')) ]
2.在应用stu\urls.py中配置
#coding=utf-8 from django.conf.urls import url import views urlpatterns=[ url(r'^hello/$',views.index_view) ]
3.在应用stu中的views.py文件中定义一个函数
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index_view(request): return HttpResponse('hello')
4.访问浏览器:输入127.0.0.1:8000/student/hello/
带参数的URLConf
.位置传参
#stu\urls.py
from django.conf.urls import url import views urlpatterns=[ url(r'^hello/(\d{4})/(\d{2})',views.index1_view) ]
#stu\views.py
def index1_view(request,num1,num2): return HttpResponse('hello_%s_%s' %(num1,num2))
.关键字传参
from django.conf.urls import url
import views urlpatterns=[ url(r'^hello1/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$',views.index2_view) ]
def index2_view(request,year,month,day): return HttpResponse('hello_%s_%s_%s' %(year,month,day))
.额外传参
from django.conf.urls import url import views urlpatterns=[ url(r'^hello2/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.index3_view,{'name':'lisi'}), ]
def index3_view(request,year,month,day,name): return HttpResponse('hello_%s_%s_%s_%s' % (year, month, day,name))
逆向解析(防止硬编码)
.模板中的超链接
通过127.0.0.1:8000/student/ 访问视图views中index_view函数 ,进入index.html文件
在index_html文件中,通过超链接去访问 name='hello' 路由地址
获取到视图views中index4_view函数中所返回的内容
#coding=utf-8 from django.conf.urls import url import views urlpatterns=[ url(r'^$',views.index_view), #逆向 url(r'^hello4/(\d{2})', views.index4_view,name='hello') ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index_view(request): return render(request,'index.html') def index4_view(request,num): return HttpResponse('index4_view_%s' %num)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="{% url 'hello' 13%}">链接1</a> </body> </html>
.视图中的重定向
通过访问127.0.0.1:8000/student/hello5/ 获取到index5_view 函数
执行index5_view 通过重定向 获取访问name ='hello' 的函数
进入index4_view 函数,通过传入的参数 返回到页面
urlpatterns=[ url(r'^$',views.index_view), #逆向 url(r'^hello4/(\d{2})', views.index4_view,name='hello'), url(r'^hello5/', views.index5_view) ]
def index4_view(request, num): return HttpResponse('index4_view_%s' % num) def index5_view(request): return HttpResponseRedirect(reverse('hello',args=(99,)))