使用Django上传多个文件并显示上传文件列表

时间:2019-05-22 21:44:05

标签: django

我正在尝试使用Django上传多个文件。选择多个文件后提交表单时,页面会重新加载并显示消息“此字段为必填”,并且文件不会上传。

models.py

from django.db import models

# Create your models here.

class Document(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.FileField(upload_to='docs/')

forms.py

from django import forms    

from .models import Document


class DocumentForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta:
        model = Document
        fields = ('file', )

views.py

def main(request):
    documents = Document.objects.all()
    if request.method == "POST":
        form = DocumentForm(request.POST and request.FILES)
        if form.is_valid():
            files = request.FILES.getlist('file')
            for f in files:
                f.save()
    else:
        form = DocumentForm()

    return render(request, 'main.html', {'form':form, 'documents':documents})

urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('main/', views.main, name='main'),
    path('admin/', admin.site.urls),
]

main.html

 <form method="POST">
                {% csrf_token %}
                {{form.as_p}}
                <input class="btn btn-primary" type="submit" name="" value="SUBMIT">
        </form>
        <table id="gallery" class="table table-bordered">
                <thead>
                  <tr>
                    <th>Documents</th>
                  </tr>
                </thead>
                <tbody>
                  {% for document in documents %}
                    <tr>
                      <td><a href="{{ document.file.url }}">{{ document.file.name }}</a></td>
                    </tr>
                  {% endfor %}
                </tbody>
              </table>

0 个答案:

没有答案