赞
踩
在Django中上传文件通常涉及到以下几个步骤:
FileField
或ImageField
(如果上传的是图片)。Form
或ModelForm
,其中包含一个FileField
。Test/app14
python manage.py startapp app14
Test/Test/settings.py
Test/Test/urls.py
- from django.contrib import admin
- from django.urls import path, include
-
- urlpatterns = [
-
- path('app14/', include('app14.urls')),
- ]
在模型中添加一个FileField
Test/app14/models.py
- from django.db import models
-
- # Create your models here.
- class Document(models.Model):
- document = models.FileField(upload_to='documents/')
创建一个表单,用于上传文件
Test/app14/forms.py
- from django import forms
- class DocumentForm(forms.Form):
- document = forms.FileField()
Test/app14/views.py
- # 文件上传
- from django.shortcuts import render, redirect
- from .forms import DocumentForm
- from .models import Document
-
- def 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 elsewhere
- return render(request, '14/success.html')
- python manage.py makemigrations app14
-
- python manage.py migrate app14
注意,文件上传的表单需要设置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>
settings
设置MEDIA_ROOT
和MEDIA_URL
Test/Test/settings.py
- # settings.py
- MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- MEDIA_URL = '/media/'
Test/app14/urls.py
- from django.urls import path
- from . import views
- from django.conf import settings
- from django.conf.urls.static import static
-
- urlpatterns = [
-
- 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)
http://127.0.0.1:8000/app14/upload_document/
Test/media/documents/赵照_-_灯塔守望人_RZHQDK0.mp3
可以看到我们上传的文件放在了,我们设置的目录下了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。