一、Django表单(form)请求:
打开的时候默认是GET请求,获取form表单的内容。
点提交的时候是POST请求,提交form表单的内容。
根据以上区别来编写获取表单内容:
from django.shortcuts import HttpResponse
from django.shortcuts import render, redirect
def login(request):
# request包含用户提交的所有信息。
error_msg = ''
if request.method == 'POST':
user = request.POST.get('user', None) //使用get方法获取'user'键值,如果没有user键,赋值None
pwd = request.POST.get('pwd', None) //get方法里的user和pwd是form表单里input对象的name属性。
if user == '123' and pwd == '123456':
return redirect('http://www.baidu.com')
else:
error_msg = '用户名或密码错误'
return render(request, 'login.html', {'error_msg':error_msg})
二、{{key}}
{{}}在html文件中指定key,通过views.py传递字典,html在客户端显示的是典对应的key值。
HTML
<span>{{error_msg}}<span>
三、HTML读取字典数据和列表
字典:使用 . 读取读典key: dict_name.key
列表:使用 .索引读取,list_name.0
views.py
def show(request):
dict_name = {'name':'樱', 'age':19, 'mail':'ying@126.com', 'fav':['football', 'sing', 'cook']}
return render(request,'home.html', dict_name)
字典HTML:
<p>{{dictname.name}}</p> \\樱
<p>{{dictname.age}}</p> \\19
<p>{{dictname.mail}}</p> \\ying@126.com
列表HTML
<p>{{list_name.0}}</p> \\football
<p>{{list_name.1}}</p> \\sing
<p>{{list_name.2}}</p> \\cook
四、HTML中for循环:
使用{%%}标记循环语句,并且使用{%endfor%}声明循环结束
{%for k, v in dict_name%}
\\HTML内容
<p>{{k}}:{{v}}</p>
{%endfor%}
//views.py
return render(request, 'index.html', {'list_name':['a','b','c']})
{%for i in list_name%}
<p>{{i}}</p> //a,b,c
{%endfor%}
五、HTML中if循环:
{%if 条件1 %}
\\HTML内容
<p>{{k}}:{{v}}</p>
{%elif 条件2%}
...
{%else%}
...
{%endfor%}
六、views.py获取html模板传入的数据
html提交的数据方法有很多种,一般使用两类:POST和GET
1、POST方法请求:一般用于修改、更新数据。
2、GET方法请求:以网址显示方式提交,例:http:\\localhost\hw\?id=1&name=david,一般用于向服务器请求数据
3、其它。put,delete,head,option....
4、上传文件类型的数据,在Form表单指定-->enctype='multipart/form-data'
views.py获取数据方法:
1、POST.get('name','默认值'),获取元素的唯一值,如果没有,赋默认值
2、POST.getlist('name','默认值'),获取多值元素的列表,如果没有,赋默认值
def get_data(request):
get_post = request.POST.get('user_name') # 获取HTML元素名为user_name的值 ,<input name='user_name'>
get_post = request.POST.get('user_name',None) # 找不到user_name元素,返回None
get_list = request.POST.getlist('favor') # 获取checkbox,multiple的HTML值
get_get = request.GET.get('user_name') # 同上
get_get = request.GET.get('user_name',None) # 同上
get_get = request.GET.getlist('user_name')
3、FILES.get('name'),获取上传的文件对象,默认显示文件名,
obj.name显示上传的文件名,
obj.chunks()迭代器读取数据块,使用for循环读取所有数据,for r in obj.chunks()
def get_file(request):
obj = request.FILES.get('file_obj')
f = open(obj.name, 'wb+') # 以上传的文件名命名。
for i in obj.chunks(): # 循环读取chunks迭代器数据。
f.write(i)
f.close()
七、views.py函数返回网址:
1、render:HTML模板路径,格式:render(request,'HTML模板名',传递的字典)
2、redirect:返回一个完整的URL(本地或网络地址) ,格式:redirect('http://www.baidu.com')或redirect('/test/') ,
test前面的/代表根,不加/当前的下级目录
3、HttpResponse:返回HTML的字符串,格式:HttpResponse('<p>这只是一个例子</p>')
def show_data(request):
v=1234
# 站内跳转
return render(request,'index.html',{"dict":v})
# 站外跳转
return redirect('http://www.baidu.com')
# 跳转站内根路径,http://ip/blog
return redirect('/blog')
# 跳转站内当前路径下一级,比如当前是http://ip/show,跳转到http://ip/show/blog
return redirect('blog/')
# 直接返回HTML字符串。
return HttpResponse('<p>警告!</p>')
上传文件示例:
urls.py
from django.conf.urls import url
from django.contrib import admin
import index.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url( r'^mains$',index.views.mains), # http://ip/mians,跳转到index目录下的views.py下的mains函数
## url( r'',index.views.mains), # http://ip,跳转到index目录下的views.py下的mains函数
url(r'^mains/up$', index.views.rev_file) # r'^ $'定义^开头$结尾,否则,所有包含此单词的地址都转向,容易混淆
]
index.html
使用了{{}},{%%},模板语言。同时上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="up" enctype="multipart/form-data" method="post">
//action,跳转到的网址,action="/up"代表 根目录+up;action="up"代表 当前网址+up
//enctype,form表单可接收文件
<input type="text" name="user_name" placeholder="Input your name..." />
<input name="up_file" type="file"/>
//type="file",代表可以上传文件型数据
<p>
文件分类:
软件<input type="checkbox" value="技术" name="f_type">
HTML<input type="checkbox" value="HTML" name="f_type">
编程<input type="checkbox" value="编程" name="f_type">
</p>
//创建多选框
<input type="submit" value="提交">
</form>
{% if f_name %} //使用if判断是否上传文件,上传文件,显示信息
<p><span style="font-style: italic">{{ u_name }}</span>,Your file:{{ f_name }} Upload Successful!</p>
分类:
{% for i in f_type %} //使用for读取选择的文件分类
{{ i }}
{% endfor %}
{% else %} //未上传文件提示
<p><span>You don't upload file!</span></p>
{% endif %}
</body>
</html>
test/views.py
from django.shortcuts import render
import os
# Create your views here.
def mains(request):
# 首次打开网址,进入的index.html页面
return render(request, 'index.html')
def rev_file(request):
# 接收form表单提交的数据
f_name = ''
u_name = ''
f_type = ''
if request.method == 'POST':
f_obj = request.FILES.get('up_file', None)
# 获取file对象,print(f_obj)是文件名,但实际是对象,因为FILES定义了__repr__或__str__
if f_obj:
#如果有上传的文件
f_name = f_obj.name
u_name = request.POST.get('user_name', None)
f_type = request.POST.getlist('f_type') #获取checkbox或multiple类型的option选项的数据
f = open(os.path.join('upload', f_name), 'wb+') #manage.py同级目录的upload文件夹
for i in f_obj.chunks(): #chunks(),迭代器,使用for读取
f.write(i)
f.close()
return render(request, 'index.html', {'f_name': f_name, 'u_name': u_name, 'f_type': f_type})
# 再返回index.html的内容,但浏览器网址会变,内容也会出现if语句的内容
request其它方法:
request.GET
request.POST
request.method
request.body 原始数据
request.path # /upload/
request.get_full_path() # /upload/?id=1
request.META 网页原信息
request.FILES 文件