问题
I want to upload multiple files in the Django admin, without having to place multiple FileField fields. The user can be able to manage the files in a simple way; delete or change each uploaded file but upload several at once.
the solution I see viable is to use several filefield but the problem is, i dont know how many files the user will upload
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):
name = models.CharField(max_length=250)
observations = models.TextField(null = True, blank = True)
number_folder = models.CharField('Folder', max_length=250)
file1 = models.FileField('file 1', upload_to=case_upload_location, null = True, blank = True)
file2 = models.FileField('file 2', upload_to=case_upload_location, null = True, blank = True)
file3 = models.FileField('file 3', upload_to=case_upload_location, null = True, blank = True)
file4 = models.FileField('file 4', upload_to=case_upload_location, null = True, blank = True)
Final Target
Multiple files to upload(user need to delete or change one by one but upload all at once).
回答1:
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
来源:https://stackoverflow.com/questions/55543232/how-to-upload-multiple-files-from-the-django-admin