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>