您好,登錄后才能下訂單哦!
一、文件上傳 方法一 上傳文件視圖函數 def upload_img(request): obj = request.FILES.get('file') #前端js設置的key img_path = os.path.join('static','img',obj.name) with open(img_path,mode='wb') as f: for chunk in obj.chunks(): f.write(chunk) data = { 'status': True, 'path': img_path } import json return HttpResponse(json.dumps(data)) 前端頁面 form表單 <form> <div class="form-group"> <label for="exampleInputFile">上傳圖片</label> <input type="file" id="exampleInputFile"> <button type="button" class="btn btn-default" id="uploadfile">上傳</button> {# <p class="help-block">Example block-level help text here.</p>#} </div> <div class="form-group"> <label for="select_news">選擇新聞類型</label> <select class="form-control" id="select_news"> <option>42區</option> <option>段子</option> <option>圖片</option> <option>挨踢1024</option> <option>你問我答</option> </select> </div> <div class="form-group"> <label for="news_url">新聞鏈接</label> <input type="text" class="form-control" id="news_url" placeholder="Url"> </div> <div class="form-group"> <label for="news_title">新聞標題</label> <textarea class="form-control" rows="3" id="news_title"></textarea> </div> <div class="form-group"> <label for="news_summary">新聞簡介</label> <textarea class="form-control" rows="3" id="news_summary"></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary" id="news_publish">提交</button> </div> </form> js 通過FormData方法處理 $(document).ready(function () { $('#uploadfile').click(function () { var formData = new FormData(); formData.append('file',$('#exampleInputFile')[0].files[0]); $.ajax({ url: '/upload', type: 'POST', data: formData, processData: false, //添加這兩個參數,表示將原生文件發到后臺 contentType: false, success: function (res) { console.log(res); } }) }) }); 方法二 前端頁面用form和iframe組合偽造ajax提交 <form method="POST" target="xxxxxx" action="/upload_img2/" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user" /> <a > 上傳 <input type="file" name="avatar" /> </a> <input type="submit" value="提交" /> </form> <iframe id="ifm" name="xxxxxx" onload="successCallback(this);" ></iframe> 注: form屬性target的值必須和iframe的name屬性值一樣 view視圖函數處理上傳請求 def upload_img2(request): response = BaseResponse() try: user = request.POST.get('user') #處理post請求 obj = request.FILES.get('avatar') #處理上傳文件 img_path = os.path.join('static', 'img', obj.name) with open(img_path,mode='wb') as f: for chunk in obj.chunks(): f.write(chunk) except Exception as e: response.msg = str(e) else: response.status = True response.data = img_path return HttpResponse(json.dumps(response.get_dict())) 二、django對mysql事務的支持 view視圖 import json from django.db.models import F # F模塊實現數據庫字段自增 from django.db import transaction #支持事務原子性,對數據庫的連續操作,操作成功必須每個sql都成功,否則都失敗 from utils.response import LikeResponse def do_like(request): """ 點贊 :param request: :return: """ response = LikeResponse() try: new_id = request.POST.get('newId') # 當前登錄用戶ID # uid = request.session.get('uid') uid = 1 exist_like = models.Like.objects.filter(nnew_id=new_id,uuser_id=uid).count() with transaction.atomic(): #事務 if exist_like: models.Like.objects.filter(nnew_id=new_id, uuser_id=uid).delete() models.News.objects.filter(id=new_id).update(like_count=F('like_count') - 1) response.code = 666 else: models.Like.objects.create(nnew_id=new_id,uuser_id=uid) models.News.objects.filter(id=new_id).update(like_count=F('like_count') + 1) response.code = 999 except Exception as e: response.msg = str(e) else: response.status = True return HttpResponse(json.dumps(response.get_dict())) 三、多級菜單,多級評論 view視圖 from django.shortcuts import render, HttpResponse, redirect # Create your views here. import json from django.db.models import F from app01 import models from django.db import transaction from utils.response import LikeResponse def comment_list(request): li = [ {'id': 1, 'user': '銀秋良', 'content': '灌我鳥事', 'parent_id': None}, {'id': 2, 'user': '銀秋良', 'content': '管我鳥事', 'parent_id': None}, {'id': 3, 'user': '型譜', 'content': '你個文盲', 'parent_id': 1}, {'id': 4, 'user': '詳解', 'content': '好羨慕你們這些沒臉的人呀', 'parent_id': 2}, {'id': 5, 'user': '銀秋良', 'content': '你是流氓', 'parent_id': 3}, {'id': 6, 'user': '銀秋良', 'content': '你冷庫無情', 'parent_id': 5}, {'id': 7, 'user': '銀秋良', 'content': '你才冷酷無情', 'parent_id': 4}, {'id': 8, 'user': '銀秋良', 'content': '你無理取鬧', 'parent_id': 4}, ] com_list = build_comment_data(li) html = build_comment_tree(com_list) return render(request, 'comment_list.html', {'comment_html': html}) #將列表子元素放入父級元素中 def build_comment_data(li): dic = {} for item in li: item['children'] = [] dic[item['id']] = item result = [] for item in li: pid = item['parent_id'] if pid: dic[pid]['children'].append(item) else: result.append(item) return result #生成 html頁面 def build_comment_tree(com_list): tpl = """ <div class='item'> <div class='title'>{0}:{1}</div> <div class='body'>{2}</div> </div> """ html = "" for item in com_list: if not item['children']: html += tpl.format(item['user'],item['content'],"") else: html += tpl.format(item['user'], item['content'], build_comment_tree(item['children'])) return html comment_list.html頁面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .body{ margin-left: 30px; } .hide{ display: none; } </style> </head> <body> <h2>評論</h2> {{ comment_html|safe }} <h2>菜單</h2> <hr/> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { $('.title').click(function () { if ($(this).next().hasClass('hide')){ $(this).next().removeClass('hide'); }else{ $(this).next().addClass('hide'); } }) }) </script> </body> </html> 四、python實現get和post請求 客戶端: import requests response = requests.get(' 傳遞字典類型參數 data_dict = { 'k1':'v1', 'k2':'v2' } content-type: application/x-www-form-urlencoded response = requests.post(' print(response.text) 傳遞json類型參數 content-type: appcation/json response = requests.post(' print(response.text) 服務端Django: from django.views.decorators.csrf import csrf_exempt,csrf_protect @csrf_exempt def asset(request): if request.method == "GET": return HttpResponse('收到:GET') else: print(request.POST) print(request.body) return HttpResponse('收到:POST')
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。