在Django中上传文件通常涉及到以下几个步骤:
- 设置你的模型以包含一个
FileField
或ImageField
(如果上传的是图片)。 - 创建一个表单,该表单包含一个
Form
或ModelForm
,其中包含一个FileField
。 - 在你的视图中处理上传的文件。
- 在你的模板中创建一个HTML表单,该表单包含一个文件输入字段。
1,创建应用
Test/app14
python manage.py startapp app14
2,注册应用
Test/Test/settings.py
3,添加应用路由
Test/Test/urls.py
from django.contrib import admin
from django.urls import path, includeurlpatterns = [path('app14/', include('app14.urls')),
]
4,添加模型
在模型中添加一个FileField
Test/app14/models.py
from django.db import models# Create your models here.
class Document(models.Model):document = models.FileField(upload_to='documents/')
5,添加表单
创建一个表单,用于上传文件
Test/app14/forms.py
from django import formsclass DocumentForm(forms.Form):document = forms.FileField()
6,添加视图函数
Test/app14/views.py
# 文件上传
from django.shortcuts import render, redirect
from .forms import DocumentForm
from .models import Documentdef upload_document(request):if request.method == 'POST':form = DocumentForm(request.POST, request.FILES)if form.is_valid():document = Document(document=request.FILES['document'])document.save()return redirect('success_url') # 重定向到成功页面else:form = DocumentForm()return render(request, '14/upload.html', {'form': form})def success_view(request):# This view can display a success message or redirect elsewherereturn render(request, '14/success.html')
7,执行迁移
python manage.py makemigrations app14python manage.py migrate app14
8,添加HTML代码
注意,文件上传的表单需要设置enctype="multipart/form-data"
属性
Test/templates/14/Upload.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><form method="post" enctype="multipart/form-data">{% csrf_token %}{{ form.as_p }}<button type="submit">Upload</button>
</form></body>
</html>
上传文件成功后,重定向至一个提示文件上传成功的页面
Test/templates/14/success.html
<!DOCTYPE html>
<html>
<head><title>Success</title>
</head>
<body><h1>File Uploaded Successfully!</h1>
</body>
</html>
9,settings
设置MEDIA_ROOT
和MEDIA_URL
Test/Test/settings.py
# settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
10,添加路由地址
Test/app14/urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import staticurlpatterns = [path('my_form_view/', views.my_form_view, name='my_form_view'),path('upload_document/', views.upload_document, name='upload_document'),path('success/', views.success_view, name='success_url'),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
11,访问页面
http://127.0.0.1:8000/app14/upload_document/
Test/media/documents/赵照_-_灯塔守望人_RZHQDK0.mp3
可以看到我们上传的文件放在了,我们设置的目录下了