4 django系列之HTML通过form标签来同时提交表单内容与上传文件

preface

我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提交文件到后台。

看看代码

我们前端使用html语言写的时候,要注意每一个input、select标签需要有name属性,这样我们后端在在获取值的时候,就以name作为key来获取对应value。

首先看看前端html页面

<form id="updatecode"  method="post" action="/BatchM/apply_update.html/apply"   enctype="multipart/form-data" role="form">   # 申明加密类型,上传文件必须这样。
        {% csrf_token %}
            <label for="exampleInputEmail1">请选择归属项目</label>
            <div>
                <select name="flow_project" id="flow_project" class="form-control">    # 都设置了name属性
                    {% for project in  projects %}
                        <option value="{{ project }}" >{{ project }}</option>
                    {% endfor %}
                </select>
            </div>

            <label for="exampleInputEmail1">请选择归属应用</label>
            <div>
                <select id="flow_app" name="flow_app" class="form-control">    # 都设置了name属性
                    {% for app in  apps %}
                        <option value="{{ app }}" >{{ app }}</option>
                    {% endfor %}
                </select>
            </div>

            <div class="form-group">
                <label for="exampleInputEmail1">哪台服务器需要更新</label>
               <!-- <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email"> -->
                <input type="text" name="target_host" class="form-control" id="target_host"  placeholder="请输入主机ip/域名">     # 都设置了name属性
            </div>
             <div class="form-group">
                <label for="exampleInputFile">附件上传</label>
                 <input  type="file" name="file" id="file_upload"> onclick="FileUpload()">开始上传附件</button> -->     # 都设置了name属性
            </div>
            '''''省略一堆类似的代码'''''
            <button type="submit" class="btn btn-success" >提交工单</button>
</form>            

我们看看后台,处理这里提交数据的逻辑代码,django作为web框架。

def apply_update_apply(request):
    '''
    显示申请更新到页面
    :param request:
    :return:
    '''
    if request.method == 'GET':    
        apps = models.TypeOfApp.objects.all()
        projects = models.TypeOfProject.objects.all()
        return render(request,'apply_update.html',{'btitle':'申请更新','apps':apps,'projects':projects})

    elif request.method == "POST":   # 提交数据

        file_obj = request.FILES.get('file')    # 使用这个 request.FILES.get方法来获取上传文件的句柄
        upload_file = None
        if file_obj:   # 处理附件上传到方法
            accessory_dir = settings.accessory_dir    # 获取上传路径,在settings配置好的
            if not os.path.isdir(accessory_dir):      # 判断是否有这个目录,没有就创建
                os.mkdir(accessory_dir)
            upload_file = "%s/%s" % (accessory_dir, file_obj.name)   #  拼接上传路径
            with open(upload_file, 'wb') as new_file:    # 开始写入文件
                for chunk in file_obj.chunks():         # 必须使用chunks方法,因为文件上传采用块上传
                    new_file.write(chunk)
  
        project_name = request.POST.get('flow_project')    # 获取表单里input标签的参数,所有get的key都是name指定的
        flow_project = models.TypeOfProject.objects.get(name_of_project=project_name)
        app_name=request.POST.get('flow_app')
        flow_app = models.TypeOfApp.objects.get(app_name=app_name)
        order_id = time.strftime("%Y%m%d%H%M%S", time.localtime())
        #print('usernane',request.user.username)      #打印用户到名字
        #print('email',request.user.email)        # 打印用户的邮箱地址
        request_set = {       # 做成一个字典,方便下一步入库,所有get的值都是在html页面通过input标签的name属性指定的。
            'OrderId':order_id,
            'username': request.user.email,   # 通过这个方法获取登陆用户的email
            'flow_project':flow_project,
            'flow_app':flow_app,
            'target_host':request.POST.get('target_host'),
            'code_source':request.POST.get('code_source'),
            'configfile_path':request.POST.get('configfile_path'),
            'configfile_content':request.POST.get('configfile_content'),
            'sql_command':request.POST.get('sql_command'),
            'crond_task':request.POST.get('crondtab_task'),
            'system_env_change':request.POST.get('change_sys_env'),
            'update_of_reason':request.POST.get('Upreason'),
            'accessory_path': upload_file
        }
        email_issend = core.selfmail(request_set)      # 调用发送邮件的功能,发送到指定到地址,成功返回True,失败返回False
        request_set['email_issend']= email_issend         
        data_obj = models.WorkOrderOfUpdate(**request_set)    
        data_obj.save()    # 保存数据
        return  HttpResponseRedirect('/BatchM/apply_update.html/search/%s'%order_id)   # 返回数据给前端

这样我们在前端提交的文本框数据以及文件都可以同时被后台处理啦。。。

原文地址:https://www.cnblogs.com/liaojiafa/p/6238235.html