简体   繁体   中英

Uploading multiple files at once - Django

I'm following the way shown below, and everything seems okay. But the problem is, I'm uploading more than photo files (by holding ctrl ), but only one of them is uploading actually. Here my codes:

views.py :

def school_document(request):
    if request.method == 'POST':
        form = CreateSchoolDocumentForm(request.POST, request.FILES, use_required_attribute=False)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('school_document')
    else:
        form = CreateSchoolDocumentForm(use_required_attribute=False)
    context = {
        'form': form
    }
    return render(request, 'school_document.html', context)

forms.py :

...
    class Meta:
        model = SchoolDocument
        fields = '__all__'
        widgets = {
            'photos': ClearableFileInput(attrs={'multiple': True}),
        }

school_document.html :

<form class="form-container" method='POST' enctype="multipart/form-data" style="height: auto;">
...
</form>

models.py :

class SchoolDocument(models.Model):
    apply_date = models.DateTimeField(_('Müraciət tarixi'))
    ...
    photos = models.FileField(upload_to='static/school_documents/', blank=True, null=True)

    def __str__(self):
        return str(self.apply_date)

This is an updated answer. Your SchoolDocument has some fields plus photo field. When you set your model this way, the photofield will only be able to accept one file.

What you need to do is having a separate Photo model and ForeignKey to your SchoolDocument model.

class SchoolDocument(models.Model):
    apply_date = models.DateTimeField(_('Müraciət tarixi'))
    ...
    

    def __str__(self):
        return str(self.apply_date)


class Photo(models.Model):
    schooldocument = models.ForeignKey(SchoolDocument, ........)
    image = models.FileField(upload_to='static/school_documents/', blank=True, null=True)

In your forms.py, you will add another field (filefield) to your SchoolDocument Form with the "multiple file" widget setting.

and in views.py, you will save invidvidual file to your Photo model

files = request.FILES.getlist('image')

for f in files:
    photo = Photo(schooldocument=schooldocument, image=f)
    photo.save()
    
    # Do something about each f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM