(更新时间)2021年4月5日 Django框架 视图和URL

150 阅读1分钟

1. 定义视图

  • 视图就是一个Python函数,被定义在应用的views.py中.
  • 视图的第一个参数是HttpRequest类型的对象reqeust,包含了所有请求信息.
  • 视图必须返回HttpResponse对象,包含返回给请求者的响应信息.
  • 需要导入HttpResponse模块 :from django.http import HttpResponse
  • 定义视图函数 : 响应字符串index给客户端
from django.shortcuts import render
from django.http import HttpRequest,HttpResponse
# Create your views here.
def index(request):
    return HttpResponse('book-index')

2. 配置URLconf

查找视图的过程 :

1.请求者在浏览器地址栏中输入URL, 请求到网站.
2.网站获取URL信息.
3.然后与编写好的URLconf逐条匹配.
4.如果匹配成功则调用对应的视图.
5.如果所有的URLconf都没有匹配成功.则返回404错误.

在这里插入图片描述
URLconf入口

"""
DjangoWeb URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/

Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

# Uncomment next two lines to enable admin:
from django.contrib import admin
#from django.urls import path
from django.conf.urls import url, include
urlpatterns = [
    # Uncomment the next line to enable the admin:
    #path('admin/', admin.site.urls)
    url(r'^admin/', admin.site.urls),
    url(r'^',include('book.urls'))
]

在子应用中添加urls.py

from django.conf.urls import url
from book.views import index
urlpatterns = [
    #index/
    # url的第一参数是:正则
    # url的第二参数是:视图函数名
    #pay/order/
    url(r'^index/$',index),
]

url匹配过程
在这里插入图片描述

3. 测试:请求访问

在这里插入图片描述

4. 总结

视图处理过程如下图:在这里插入图片描述
使用视图时需要进行两步操作,两步操作不分先后

  • 配置URLconf
  • 在应用/views.py中定义视图