0

I have created a webpage where a candidate can apply for jobs. There, they can list different previous experiences. I am handling all experience details by concatenating them in my models and splitting them while fetching. how should I handle files in such a case?

My Applicant model has the FileField called company_doc. Can it also somehow take multiple files so that I can retrieve them via some indexing? is that possible?

HarshitaJaya
  • 9
  • 1
  • 3
  • Please show your code it will be easier to understand – Papis Sahine Oct 09 '21 at 08:12
  • @HarshitaJaya: there is no *builtin* model field that takes multiple files, and if there was, that would probably be bad design. Usually one creates a model named `CompanyDoc` with a `FileFIeld` and a `ForeignKey` to the `Applicant` model. – Willem Van Onsem Oct 09 '21 at 08:16

1 Answers1

0

There is, at the moment of writing, no FileField for a model that can store multiple files. Usually this is modelled with an extra model, for example CompanyDoc that has a FileField and a ForeignKey to the Applicant model, so:

class Applicant(models.Model):
    # …
    pass

class CompanyDoc(models.Model):
    applicant = models.ForeignKey(
        Applicant, on_delete=models.CASCADE
    )
    file = models.FileField(upload_to='company_doc/')

You can then construct a form that can upload multiple files with:

from django import forms

class CompanyDocsForm(forms.Form):
    files = forms.FileField(
        widget=forms.ClearableFileInput(attrs={'multiple': True})
    )

and then process this with:

def some_view(request, applicant_id):
    if request.method == 'POST':
        form = CompanyDocForm(request.POST, request.FILES)
        if form.is_valid():
            data = [
                CompanyDoc(file=file, applicant_id=applicant_id)
                for file in request.FILES.getlist('files')
            ]
            CompanyDoc.objects.bulk_create(data)
        else:
            # …
            pass
    else:
        # …
        pass
    # …

For more information, see the Uploading multiple files section of the documentation.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555