django搭建web (五) views.py

http请求: HttpRequest

http响应: HttpResponse

所在位置:django.http

isinstance(request,HttpResponse) True->request的类型就是HttpRequest

HttpRequest对象属性:

Attribute Description
path 请求页面的全路径
method ```请求中使用的HTTP方法的字符串表示。全大写表示。例如

       if quest.method == 'GET':

do_something()

elif request.method == 'POST': 

do_something_else() ```

|GET |包含所有HTTP GET参数的类字典对象 |

|POST |包含所有HTTP POST参数的类字典对象 |

    localhost:8000/hello/?name=12345

参数名为name,在接收的时候可以如下

    def hello(request):
print(quest.GET.get('name'))
get() 如果key对应多个value,get()返回最后一个value

form-表单

response = HttpResponse("Here is the text of the web page",mimetype="text/plain")
return response
#等价
return render(request,'table.html',{'foo':'bar'}) t = loader.get_template('table.html')
c = {'foo':'bar'}
return HttpResponse(t.render(c,request),content_type="text/html") from django.shortcuts import render_to_response
return render_to_response('table.html',{'foo':'bar'})

redirect 页面跳转

from django.shortcuts import redirect
... ...
return redirect('http://www.baidu.com')

locals()

#locals()将当前作用于的变量全部传递给模板变量
return render_to response('table.html',locals())

demo

# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.shortcuts import render
from .models import myQuestion,myAnswer
# Create your views here. def research(request):
question_list = myQuestion.objects.all()
answer_list = myAnswer.objects.all()
context = {'question_list':question_list,'answer_list':answer_list}
return render(request,"polls/index.html",context)

在该demo中

首先从models中引入模型myQuestion,myAnswer

from .models import myQuestion,myAnswer

其次定义了一个函数hello,这个地方的hello名称要与urls.py中名称对应,例如hello出现在urls.py如下:

urlpatterns = [
url(r'^$',views.hello,name = 'hello'),
]

之后调用

question_list = myQuestion.objects.all()

函数,将myQuestion模型的全部变量以列表形式赋值给question_list,下句类似

然后

context = {'question_list':question_list,'answer_list':answer_list}

将列表转成字典,并起上名称,一同赋值给context

最后

return render(request,"polls/index.html",context)

将内容context放进templates/polls/index.html文件中渲染,显示

上一篇:PyCharm社区版+Django搭建web开发环境-2


下一篇:python +Django 搭建web开发环境初步,显示当前时间