[Django]-How to upload multiple files from the Django admin?

10đź‘Ť

âś…

Looks like you’re in need one-many foreign key relationship from a “Case File” model to the “Case” model you’ve defined.

models.py

from django.db import models

def case_upload_location(instance, filename):
    case_name = instance.name.lower().replace(" ", "-")
    file_name = filename.lower().replace(" ", "-")
    return "casos/{}/{}".format(case_name, file_name)

class Case(models.Model):
    # datos del caso
    name = models.CharField('Nombre', max_length=250)
    observations = models.TextField('Observaciones', null = True, blank = True)
    number_folder = models.CharField('Numero de Carpeta', max_length=250)

class CaseFile(models.Model):
    case = models.ForeignKey(Case, on_delete=models.CASCADE) # When a Case is deleted, upload models are also deleted
    file = models.FileField(upload_to=case_upload_location, null = True, blank = True)

You can then add a StackedInline admin form to add Case Files directly to a given Case.

admin.py

from django.contrib import admin
from .models import Case, CaseFile

class CaseFileAdmin(admin.StackedInline):
    model = CaseFile

@admin.register(Case)
class CaseAdmin(admin.ModelAdmin):
    inlines = [CaseFileAdmin]

@admin.register(CaseFile)
class CaseFileAdmin(admin.ModelAdmin):
    pass

Leave a comment