使用 Django Forms 上傳檔案

首先,我們需要將 MEDIA_ROOTMEDIA_URL 新增到我們的 settings.py 檔案中

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

在這裡你將使用 ImageField,所以請記住在這種情況下安裝 Pillow 庫(pip install pillow)。否則,你會有這樣的錯誤:

ImportError: No module named PIL

Pillow 是 PIL 的一個分支,即 Python 成像庫,不再維護。Pillow 向後相容 PIL。

Django 帶有兩個表單欄位來上傳檔案到伺服器 FileFieldImageField,以下是我們表單中使用這兩個欄位的示例

forms.py:

from django import forms

class UploadDocumentForm(forms.Form):
    file = forms.FileField()
    image = forms.ImageField()

views.py:

from django.shortcuts import render
from .forms import UploadDocumentForm

def upload_doc(request):
    form = UploadDocumentForm()
    if request.method == 'POST':
        form = UploadDocumentForm(request.POST, request.FILES)  # Do not forget to add: request.FILES
        if form.is_valid():
            # Do something with our files or simply save them
            # if saved, our files would be located in media/ folder under the project's base folder
            form.save()
    return render(request, 'upload_doc.html', locals())

upload_doc.html:

<html>
    <head>File Uploads</head>
    <body>
        <form enctype="multipart/form-data" action="" method="post"> <!-- Do not forget to add: enctype="multipart/form-data" -->
            {% csrf_token %}
            {{ form }}
            <input type="submit" value="Save">
        </form>
    </body>
</html>