Here's the model
class Document(models.Model):
file = models.FileField()
The template
{% extends 'another-form.html' %}
{% block content %}
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{% bootstrap_field form.files %}
<button >Upload</button>
</form>
{% endblock %}
Form class and view:
from django import forms
from django.urls import reverse_lazy
from django.views.generic import FormView
class UploadDocumentForm(forms.Form):
files = forms.FileField(widget=forms.FileInput(attrs={'multiple': True}), label='')
class UploadDocumentView(FormView):
template_name = 'upload-document.html'
form_class = UploadDocumentForm
success_url = reverse_lazy('upload-document')
def form_valid(self, form):
Document.objects.bulk_create([Document(file=f) for f in self.request.FILES])
return super().form_valid(form)
when the form is submitted, I get these responses:
[02/Jan/2023 14:43:13] "POST /upload-document/ HTTP/1.1" 302 0
[02/Jan/2023 14:43:14] "GET /upload-document/ HTTP/1.1" 200 70636
[02/Jan/2023 14:43:17] "GET /upload-document/ HTTP/1.1" 200 70635
and nothing is uploaded to settings.MEDIA_ROOT
which is specified in settings.py
and works for models.ImageField
. I also tried
file = models.FileField(upload_to=settings.MEDIA_ROOT)
which is useless, just included for completeness, also:
class UploadDocumentForm(forms.Form):
files = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': True}), label=''
)
CodePudding user response:
you're dealing with multiple files, so you should use getlist instead. eg:
Document.objects.bulk_create([Document(file=f) for f in self.request.FILES.getlist('files'])