Django文件上传不起作用可能是由于以下原因:
enctype="multipart/form-data"
,例如:<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
request.FILES
来获取上传的文件,例如:def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
# 处理文件
return redirect('success')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
# models.py
class Document(models.Model):
file = models.FileField(upload_to='documents/')
# forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = Document
fields = ['file']
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
如果以上方法都不能解决问题,请检查Django的日志和服务器日志,以查找更多详细的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云