首页 > 其他分享 >16-项目实战-上传文件-实战

16-项目实战-上传文件-实战

时间:2023-02-01 11:57:13浏览次数:53  
标签:实战 name form 16 list request upload path 上传

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

相关文章

  • 15-项目实战-上传文件-配置media
    #在django的开发过程中有两个特殊的文件夹:static:存放静态文件的路径,包括:CSS,JS,项目图片.media:用户上传的数据.1.配置media#启用media:在根目录......
  • 14-项目实战-图形页面
    #第三方js插件1.highchart国外:https://www.hcharts.cn/demo/highcharts/column-basic2.echats国内(推荐):https://echarts.apache.org/handbook/zh/g......
  • 13-项目实战-订单管理
    #1.依赖bootstrap.py-ModelForm#2.依赖pagemtion.py-分页1.创建订单管理表classBill(models.Model):"""订单管理"""oid=models.CharField(verbos......
  • [转]Outlook 2016需要更新才能启动?
     原文:https://www.cnblogs.com/jessepeng/p/16698042.html------------------问题Outlook2016一直好好地,最近打开弹窗“需要更新才能启动”,收不了邮件。解决在Mic......
  • ASP.NET 前端大文件上传
    ​ 以ASP.NETCoreWebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API,包括文件的上传和下载。 准备文件上传的API #region 文件上传......
  • SpringBoot 前端大文件上传
    ​ 最近遇见一个需要上传百兆大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现。在某些业务中,大文件上传是一个比较重要的......
  • 简单三步上传公众号文章附件
     网址:https://uom.cn/f/# 第一步:打开网站,微信扫码登录,会自动返回主页 第二步:点击选择文件按钮 第三步:选择文件并打开  此时上传就已经完成了,会提供三个方......
  • 自定义上传图片(自定义上传input样式)
    ##1.Html文件<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>Docum......
  • [记]Rust上传库到crates.io失败的解决办法参考
    1.SSL验证失败fatal:unabletoaccess'https://github.com/rust-lang/crates.io-index/':OpenSSLSSL_read:Connectionwasreset,errno10054取消git的SSL验证gi......
  • 弱网测试利器-Charles工具实战
    每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试,领取资料可加:magetest码同学抖音号:小码哥聊软件测试一:弱网测......