<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
批量上传
</div>
<form method="post" enctype="multipart/form-data" action="/depart/multi/">
{% csrf_token %}
<div class="form-group">
<input type="file" name="exc">
</div>
<input type="submit" value="上传" class="btn btn-info btn-sm">
</form>
</div>
def depart_multi(request):
from openpyxl import load_workbook
file_object = request.FILES.get("exc")
# 对象传递给openpyxl,由openpyxl读取文件
wb = load_workbook(file_object)
sheet = wb.worksheets[0]
cell = sheet.cell(1, 2)
print(cell.value)
# 循环获取每一行数据
for row in sheet.iter_rows(min_row=2):
text = row[0].value
exists = models.Department.objects.filter(title=text).exists()
if not exists:
models.Department.objects.create(title=text)
# print(type(file_object))
return redirect('/depart/list/')
{% extends 'layout.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> {{title}} </h3>
</div>
<div class="panel-body">
<form class="form-horizontal" enctype="multipart/form-data" method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{field.label}}</label>
{{field}}
<span style="color: red;" >{{field.errors.0}}</span>
<!--<input type="text" class="form-control" placeholder="标题" name="title" />-->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div></div>
</div>
{% endblock %}
def upload_form(request):
title = "Form上传"
if request.method == "GET":
form = UpForm()
return render(request, 'upload_form.html', {'form': form, "title": title})
form = UpForm(data=request.POST, files=request.FILES)
if form.is_valid():
print(form.cleaned_data)
# 读取图片内容, 写入到文件夹中,并获取文件的路径
img_object = form.cleaned_data.get('img')
file_path = os.path.join("static", "image", img_object.name)
f = open(file_path, mode='wb')
# print(type(file_path))
for chunk in img_object.chunks():
f.write(chunk)
f.close()
file_path = str(file_path)
print(form.cleaned_data)
# 将图片的文件路径,写入到数据库中
models.Boss.objects.create(
name=form.cleaned_data['name'],
age=form.cleaned_data['age'],
img=file_path,
)
return HttpResponse('...')
return render(request, 'upload_form.html', {'form': form, "title": title})
class UpForm(forms.Form):
bootstrap_exclude_fields = ['img']
def __init__(self, *args, **kwargs): # 重新定义函数,循环标签,改变样式
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
if name in self.bootstrap_exclude_fields:
continue
if field.widget.attrs:
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label
else:
field.widget.attrs = {'class': 'form-control', "placeholder": field.label}
name = forms.CharField(label="姓名")
age = forms.IntegerField(label="年龄")
img = forms.FileField(label="头像")
class Boss(models.Model):
''' 老板 '''
name = models.CharField(verbose_name='姓名', max_length=32)
age = models.IntegerField(verbose_name="年龄")
img = models.CharField(verbose_name="头像", max_length=128)