Looking for django Keywords? Try Ask4Keywords

Django 使用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成像庫,不再維護。枕頭向後兼容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>