1. 创建数据表
class UserInfo(models.Model):
"""用户信息"""
name = models.CharField(verbose_name="姓名", max_length=32)
age = models.IntegerField(verbose_name="年龄")
img = models.CharField(verbose_name="头像", max_length=128)
class CityInfo(models.Model):
"""城市信息"""
name = models.CharField(verbose_name="名称", max_length=32)
count = models.IntegerField(verbose_name="人口")
# 本质上数据库也是CharField字符串,自动保存数据
# upload_to="city/":上传到那个目录,上传到media中的city目录
img = models.FileField(verbose_name="Logo", max_length=128, upload_to="city/")
# python manage.py makemigrations
# python manage.py migrate
2. 创建路由(url)
from bbc_list.views import login, home_page, order, phone, admin, task, bill, chart, upload, city
urlpatterns = [
# 上传文件
path("upload/list/", upload.upload_list),
path("upload/form/", upload.upload_form),
path("upload/model/form/", upload.upload_model_form),
# 城市列表
path("city/list/", city.city_list),
path("city/add/", city.city_add),]
3. 编写视图函数(views-upload.py)
from django.http import HttpResponse
from django.shortcuts import render
from bbc_list import models
def upload_list(request):
"""上传文件"""
if request.method == "GET":
return render(request, "upload_list.html")
# print(request.POST) # 请求体中的数据 : 'username': ['123']
# print(request.FILES) # 请求发过的文件{}: <MultiValueDict:
# {'avatar': [<InMemoryUploadedFile: 123.xls (application/vnd.ms-excel)>]}>
file_object = request.FILES.get("avatar") # 文件对象
print(file_object.name) # 获取文件名
f = open(file_object.name, mode="wb") # 打开一个文件流
for chunk in file_object.chunks(): # 循环读取文件块
f.write(chunk) # 将提交的文件写入到文件中
f.close() # 关闭文件流
return HttpResponse("...")
from django import forms
from bbc_list.utils.bootstrap import BootStrapForm
class UpForm(BootStrapForm):
bootstrap_exclude_fields = ["img"] # 图片不添加样式
# 重新定义字段
name = forms.CharField(label="姓名")
age = forms.CharField(label="年龄")
img = forms.FileField(label="头像")
def upload_form(request):
"""form文件上传处理"""
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=", form.cleaned_data)
# {'name': 'coco', 'age': '18', 'img': <InMemoryUploadedFile: 123.png (image/png)>}
# 1.读取图片内容,写入到文件夹中,并获取文件路径
image_object = form.cleaned_data.get("img")
import os
# 数据库保存的图片,拼接上id+端口就能直接访问
# from django.conf import settings
# file_path = "bbc_list/static/img/{}".format(image_object.name)
# media_path = os.path.join(settings.MEDIA_ROOT, file_path) # settings.MEDIA_ROOT: 代表的是用户上传后的文件一般保存的地方
media_path = os.path.join("media", image_object.name) # 使用media文件夹,需要配置
f = open(media_path, mode="wb")
for chunk in image_object.chunks(): # 是对文件切片不是对读出来的切片
f.write(chunk)
f.close()
# 2.将图片文件路径写入到数据库
models.UserInfo.objects.create(
name=form.cleaned_data["name"],
age=form.cleaned_data["age"],
img=media_path
)
return HttpResponse("...")
return render(request, "upload_form.html", {"form": form, "title": title})
from bbc_list.utils.bootstrap import BootStrapModelForm
class UpModelForm(BootStrapModelForm):
bootstrap_exclude_fields = ["img"]
class Meta:
model = models.CityInfo
fields = "__all__"
def upload_model_form(request):
"""modelForm处理文件上传"""
if request.method == "GET":
title = "modelform上传文件"
form = UpModelForm()
return render(request, "upload_form.html", {"form": form, "title": title})
form = UpModelForm(data=request.POST, files=request.FILES)
if form.is_valid():
# 对于文件自动保存
# 字段 + 上传的路径写入到数据库中
form.save()
return HttpResponse("成功")
return render(request, "upload_form.html")
4. 编写html页面
4.1 upload_list.html
# upload_list.html
{% extends "one.html" %}
{% block content %}
<div class="container">
<!-- enctype="multipart/form-data": 支持提交图片-->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="username">
<input type="file" name="avatar">
<input type="submit" value="提交">
</form>
</div>
{% endblock %}
4.2 upload_form.html
{% extends "one.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">
<!-- novalidate: 关掉浏览器的校验-->
<form method="post" enctype="multipart/form-data" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>{{ field.label }}</label>
<!-- <input type="text" class="form-control" placeholder="姓名" name="user">-->
{{ field }}
<span style="color:red;"> {{ field.errors.0 }}</span>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">提 交</button>
</form>
</div>
</div>
</div>
{% endblock %}
标签:实战,name,form,16,list,request,upload,path,上传
From: https://www.cnblogs.com/kh-1314/p/17059735.html