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)   # 返回數據給前端

這樣我們在前端提交的文本框數據以及文件都可以同時被后台處理啦。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM