表单数据
template
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
boy:<input type="radio" name="gender" value="boy">
girl:<input type="radio" name="gender" value="girl"><br>
爱好:吃饭<input type="checkbox" name="favor" value="food">
钓鱼<input type="checkbox" name="favor" value="fish">
洗澡<input type="checkbox" name="favor" value="toilent"><br>
类型:<select name="leixing" multiple>
<option value="aaa">可爱</option>
<option value="bbb">白痴</option>
<option value="ccc">另类</option>
</select>
<br><input type="submit" value="submit">
</form>
urls.py 略
view.py
def index(request):
if request.method == 'POST':
username = request.POST.get("username")
password = request.POST.get("password")
gender = request.POST.get("gender")
favor = request.POST.getlist("favor")
leixing = request.POST.getlist("leixing")
print("username:%s----password:%s-----gender:%s" % (username, password, gender))
print(favor)
print(leixing)
return redirect('/')
else:
return render(request, 'index.html')
文件上传
template
<form method="post" action="{% url 'index' %}" enctype="multipart/form-data">
{% csrf_token %}
文件上传:<input type="file" name="file">
<br><input type="submit" value="submit">
</form>
view.py
from django.shortcuts import render, redirect
import os
# Create your views here.
def index(request):
if request.method == 'POST':
obj = request.FILES.get("file")
#obj: 文件的对象 obj.name:文件名 obj.chunks():文件一点一点上传到服务器
#print(obj, obj.name, obj.chunks())
#为了把文件上传到static下,拼接路径 例:static/abc123.jpg
filepath = os.path.join('static', obj.name)
#把文件一点一点写入static/abc123.jpg
with open(filepath, 'wb') as f:
for i in obj.chunks():
f.write(i)
return redirect('/')
else:
return render(request, 'index.html')