您现在的位置是:网站首页> 编程资料编程资料
python的django写页面上传文件及遇到的问题小结_python_
2023-05-26
255人已围观
简介 python的django写页面上传文件及遇到的问题小结_python_
首先上结构
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,接下来获取上传文件,指定上传路径,如果路径不存在就创建一个,把上传文件内容写到指定路径下
再来是templates/5/upload.html
//这个是错误的//这个是错误的
指定了一个action,{% url 'app5:upload_file' %},app5是app5/urls.py中的app_name,upload_file则是要跳转连接,同时因为url已经指定这个连接要跳转的views中的功能,因此这个就是app5/view.py里面的upload_file方法
这个页面展示是正常的,但是在写好功能以后,无论怎么点提交,都没法跳转到upload_file功能
仔细看表单的名称 最后是mynode/urls.py 指定app5跳转到app5/urls.py 最后打开浏览器,输入链接http://localhost:8000/app5/show_upload/ 选择要上传的文件,点击upload_file按钮 这里跳转到upload_file路径,并且显示上传文件成功 到此这篇关于python的django写页面上传文件以及遇到的问题的文章就介绍到这了,更多相关python django上传文件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('app5/', include('app5.urls')), ]

相关内容
- Python实现自动化处理Word文档的方法详解_python_
- Python Numpy教程之排序,搜索和计数详解_python_
- Python中打包和解包(*和**)的使用详解_python_
- Python NumPy教程之二元计算详解_python_
- Python Pyinstaller库安装步骤以及使用方法_python_
- 利用Pycharm将python文件打包为exe文件的超详细教程(附带设置文件图标)_python_
- Python sklearn转换器估计器和K-近邻算法_python_
- Python 模拟死锁的常见实例详解_python_
- 如何使用Pytorch完成图像分类任务详解_python_
- pytorch模型转onnx模型的方法详解_python_
