欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python的django寫頁面上傳文件及遇到的問題小結

 更新時間:2022年08月31日 08:43:08   作者:咻_python  
這篇文章主要介紹了python的django寫頁面上傳文件以及遇到的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

首先上結構

mynode -> app5 -> urls.py & views.py
| -> templates -> 5 -> upload.html
| -> mynode -> urls.py
| -> media

按照順序,先上app5/urls.py

from django.urls import path
from app5 import views as v5
app_name = 'app5'
urlpatterns = [
    path('upload_file/', v5.upload_file, name = 'upload_file'),
    path('show_upload/', v5.show_upload, name = 'show_upload'),
]

path('upload_file/', v5.upload_file, name = 'upload_file'),指定upload_file跳轉功能
path('show_upload/', v5.show_upload, name = 'show_upload'),指定show_upload跳轉功能

接著是app5/view.py

from django.shortcuts import render
from django.http import HttpResponse
import os
def show_upload(request):
  return render(request, '5/upload.html')
def upload_file(request):if request.method == 'POST':
    get_file = request.FILES.get('myfile',None)
    if get_file:
      path = 'media/uploads'
      if not os.path.exists(path):
        os.makedirs(path)
      dest = open(os.path.join(path,get_file.name),'wb+')
      for chunk in get_file:
        dest.write(chunk)
      dest.close()
      return  HttpResponse('上傳文件成功!')
    else:
      return HttpResponse('沒有上傳文件!')

首先寫了一個show_upload方法,跳轉到初始頁面

接下來是upload_file方法,首先判斷請求方式是否是POST,接下來獲取上傳文件,指定上傳路徑,如果路徑不存在就創(chuàng)建一個,把上傳文件內容寫到指定路徑下

再來是templates/5/upload.html

<!--<from enctype="multipart/form-data" action="{% url 'app5:upload_file' %}" method="post">--> //這個是錯誤的
<form enctype="multipart/form-data" action="{% url 'app5:upload_file' %}" method="post">
    {% csrf_token %}
    <input type="file" name="myfile" />
    <br/>
    <input type="submit" value="upload_file" />
</form>
<!--</from>--> //這個是錯誤的

指定了一個action,{% url 'app5:upload_file' %},app5是app5/urls.py中的app_name,upload_file則是要跳轉連接,同時因為url已經(jīng)指定這個連接要跳轉的views中的功能,因此這個就是app5/view.py里面的upload_file方法

這個頁面展示是正常的,但是在寫好功能以后,無論怎么點提交,都沒法跳轉到upload_file功能

仔細看表單的名稱<from,這個坑我踩了好久,后來仔細看了下,應該是form,改了之后就好使了

最后是mynode/urls.py

from django.contrib import adminfrom django.urls import path,include

urlpatterns = [
  path('admin/', admin.site.urls),
  path('app5/', include('app5.urls')),
]

指定app5跳轉到app5/urls.py

最后打開瀏覽器,輸入鏈接http://localhost:8000/app5/show_upload/

選擇要上傳的文件,點擊upload_file按鈕

這里跳轉到upload_file路徑,并且顯示上傳文件成功

到此這篇關于python的django寫頁面上傳文件以及遇到的問題的文章就介紹到這了,更多相關python  django上傳文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論