問題描述:
在寫bbs專案的時候,老師用的是Django1.X結合富文字編輯器kindeditor,實現了圖片上傳,但是我在用Django3.X的時候,程式碼和老師一模一樣,上傳圖片的時候一直轉圈圈???但是資料夾article_img已經建立,並且圖片已經成功上傳到服務端。
如下圖:
各部分程式碼截圖如下
add_article.html
{% extends 'backend/backend_base.html' %} {% block article %} <h3>新增文章</h3> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>標題</p> <div> <input type="text" name="title" class="form-control"> </div> <p>內容</p> <div> <textarea name="content" id="id_content" cols="60" rows="10"></textarea> </div> <p>分類</p> <div> {% for category in category_list %} <input type="radio" value="{{ category.pk }}" name="category">{{ category.name }} {% endfor %} </div> <p>標籤</p> <div> {% for tag in tag_list %} <input type="checkbox" value="{{ tag.pk }}" name="tag">{{ tag.name }} {% endfor %} </div> <input type="submit" class="btn btn-danger"> </form> {% endblock %} {% block js %} {% load static %} <script charset="utf-8" src="{% static 'kindeditor/kindeditor-all-min.js' %}"></script> <script> KindEditor.ready(function (K) { window.editor = K.create('#id_content', { width : '100%', height:'700px', resizeType:1, uploadJson : '/upload_image/', extraFileUploadParams : { 'csrfmiddlewaretoken':'{{ csrf_token }}' } } ); }); </script> {% endblock %}
urls.py
# 上傳圖片 path(r'upload_image/', views.upload_image),
views.py
import os from BBS20230205 import settings def upload_image(request): back_dic = {'error': 0, } if request.method == 'POST': file_obj = request.FILES.get('imgFile') file_dir = os.path.join(settings.BASE_DIR, 'media','article_img') if not os.path.isdir(file_dir): os.mkdir(file_dir) file_path = os.path.join(file_dir, file_obj.name) with open(file_path, 'wb') as f: for line in file_obj: f.write(line) back_dic['url'] = '/media/article_img/%s' %file_obj.name return JsonResponse(back_dic)
經過我的百度,終於找到了答案:只需要在settings.py中寫下面一句程式碼:
X_FRAME_OPTIONS = 'ALLOWALL'
趕緊記錄成部落格,讓大家也可以避坑,自己下次也可以方便找到答案!!!