使用 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>