1. view
class UpForm(BootStrapForm): 封装了bootstrap的Form组件的类, 让表单快速获得bootstrap的样式
bootstrap_exclude_fields = ['img'] # 在BootStrapForm中,排除img表单的样式
name = forms.CharField(label="姓名")
age = forms.IntegerField(label="年龄")
img = forms.FileField(label="头像")
def upload_form(request):
title = "表格上传"
if request.method == "GET":
form = UpForm()
return render(request, 'upload_form.html', {'form':form, "title":title})
if request.method == "POST":
# 获取前端用户提交的数据
form = UpForm(data=request.POST, files = request.FILES)
if form.is_valid():
image_object = form.cleaned_data.get("img")
# 对图片数据进行特殊处理
db_file_path = os.path.join('static', 'img', image_object.name)
file_path = os.path.join('app01', db_file_path)
print(file_path)
f = open(file_path, mode="wb")
for chunk in image_object.chunks():
f.write(chunk)
f.close()
# 写入数据库
models.Boss.objects.create(
name = form.cleaned_data['name'],
age = form.cleaned_data['age'],
img = db_file_path,
)
return render(request, 'upload_form.html', {'form': form, "title": title})
2. template
<form method="post" novalidate enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
{{ field }}
<span style="color: red">{{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提交</button>
</form>
3. router
path('upload/form/', upload.upload_form)
本站文章除单独注明外均为原创,本文链接https://bowmanjin.com/321,未经允许请勿转载。
请先
!