Django 不会上传和保存文档
Django won't upload and save document
你看看有什么问题吗?我没有任何错误,一切都在显示,但是当我上传文件时,没有任何反应,文件没有上传。一切都应该如此,但我错过了一些东西,为什么不上传文件?
my_app/forms.py
class UploadFileForm(forms.Form):
file = forms.FileField()
my_app/hendle_file.py
def handle_uploaded_file(f):
with open('my_app/static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
my_app/views.py
from .forms import UploadFileForm
from .handle_file import handle_uploaded_file
def upload_file(request):
form = UploadFileForm()
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
print(form.cleaned_data)
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('file uploaded')
else:
form = UploadFileForm()
return render(request, 'my_app/uploadfile.html', {'form': form})
my_app/template/my_app/uploadfile.html
{% extends "my_app/base.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>
{% endblock content %}
要在表单中上传文件,必须将 enctype
属性设置为 multipart/form-data
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>
你看看有什么问题吗?我没有任何错误,一切都在显示,但是当我上传文件时,没有任何反应,文件没有上传。一切都应该如此,但我错过了一些东西,为什么不上传文件?
my_app/forms.py
class UploadFileForm(forms.Form):
file = forms.FileField()
my_app/hendle_file.py
def handle_uploaded_file(f):
with open('my_app/static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
my_app/views.py
from .forms import UploadFileForm
from .handle_file import handle_uploaded_file
def upload_file(request):
form = UploadFileForm()
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
print(form.cleaned_data)
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('file uploaded')
else:
form = UploadFileForm()
return render(request, 'my_app/uploadfile.html', {'form': form})
my_app/template/my_app/uploadfile.html
{% extends "my_app/base.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>
{% endblock content %}
要在表单中上传文件,必须将 enctype
属性设置为 multipart/form-data
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>