from django.shortcuts import render
from django.shortcuts import HttpResponse
import os
# Create your views here.
error_msg = ''
def register(request):
if request.method == 'POST':
username = request.POST.get('username')
passwd = request.POST.get('passwd')
email = request.POST.get('email')
tel = request.POST.get('tel')
photo = request.FILES.get('file')
uploadfile = os.path.join('upload',photo.name)
with open(uploadfile,'wb') as fileobj:
for chunk in photo.chunks():
fileobj.write(chunk)
if username == None or passwd == None or email == None or tel == None:
error_msg = '不能为空,请重新输入!'
return render(request, 'regist/register.html', {'error_msg': error_msg})
else:
print('准备输入mysql')
return HttpResponse('注册成功')
elif request.method == 'GET':
return render(request,'regist/register.html',{'error_msg': ''})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<div id="t2" class="header-r">
<form name="register_form" id="register_form" action="/regist/" method="post" enctype="multipart/form-data">
<h4>输入账户信息</h4>
<input type="text" id="username" name="username" placeholder="用户名"/>
<input type="password" id="passwd" name="passwd" placeholder="密码"/>
<input type="text" id="email" name="email" placeholder="邮箱"/>
<input type="text" id="tel" name="tel" placeholder="电话"/>
<input type="file" id="file" name="file"/>
<!--<input type="button" value="login" />-->
<input type="submit" value="确定注册" />
<p style="color: red">{{ error_msg }}</p>
</form>
<p style="color: red">{{ error_msg }}</p>
</div>
</body>
</html>
urls.py会传给views.fun 一个request变量,包含所有http参数。
request.method 包括get和post,post里,fun可以获取表单传过来的参数,然后进行orm操作。
表单还可以传文件到服务端,不过表单里要写enctype="multipart/form-data",在服务端指定存到路径。
另外,如果表单里有checkbox这种多选的input类型,在后台收到的就是一个list,需要用list = request.POST.getlist.