ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 视图 * 在django中,视图对WEB请求进行回应 * 视图接收reqeust对象作为第一个参数,包含了请求的信息 * 视图就是一个Python函数,被定义在views.py中 ~~~ #coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse("index") def detail(request,id): return HttpResponse("detail %s" % id) ~~~ * 定义完成视图后,需要配置urlconf,否则无法处理请求 ### URLconf * 在Django中,定义URLconf包括正则表达式、视图两部分 * Django使用正则表达式匹配请求的URL,一旦匹配成功,则调用应用的视图 * 在test1/urls.py插入booktest,使主urlconf连接到booktest.urls模块 >[warning] 注意:只匹配路径部分,即除去域名、参数后的字符串 ~~~ url(r'^', include('booktest.urls')), ~~~ 在booktest中的urls.py中添加urlconf ~~~ from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^([0-9]+)/$', views.detail), ] ~~~ ~~~ # views.py #!usr/bin/python # -*- coding: utf-8 -*- from django.shortcuts import render from .models import * # 引入模型类 # from django.http import * # from django.template import RequestContext, loader def index(request): # temp = loader.get_template('booktest/index.html') # return HttpResponse(temp.render()) booklist = BookInfo.objects.all() context = {'list': booklist} return render(request, 'booktest/index.html', context) def show(request, id): book = BookInfo.objects.get(pk=id) herolist = book.heroinfo_set.all() context = {'list': herolist} return render(request, 'booktest/show.html', context) ~~~ ~~~ # urls.py #!/usr/bin/env python # -*- coding: utf-8 -*- ''' @Time : 6/5/18 2:17 AM @Author : haibo @File : urls.py ''' from django.conf.urls import url from . import views urlpatterns = [ url(r'^[index]*$', views.index), url(r'^(\d+)$', views.show), ] ~~~