💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### 视图 * 在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), ] ~~~