• Django 文件的上传


    案例一(上传,读取到数据库,在前端显示)

    在这里插入图片描述

    html

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    视图函数

    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/')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    案例二(通过Form上传)

    在这里插入图片描述

    html

    {% 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 %}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    视图函数

    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})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    数据部分

    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="头像")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    
    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    【计算机网络篇】计算机网络的性能指标
    MySQL-查询数据库(二)
    Spring注解简析
    动态规划-买股票的最佳时机三
    第6章 使用java Config 方式实现 SpringIoc
    基于C语言 --- 自己写一个通讯录
    高等教育学:教育目的与教育制度
    DocumentType类型
    springboot基于微信小程序的校园外卖系统毕业设计源码091024
    Mac上在vm虚拟机上搭建Hadoop集群并安装zookeeper hive hbase
  • 原文地址:https://blog.csdn.net/qq_53817374/article/details/127436746