如何从Django管理员上传多个文件?

问题描述 投票:1回答:1

我想在Django管理员中上传多个文件,而不必放置多个FileField字段。用户可以以简单的方式管理文件;删除或更改每个上传的文件,但一次上传几个。

我认为可行的解决方案是使用多个文件域,但问题是,我不知道用户将上传多少文件

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)

最终目标

要上传的多个文件(用户需要逐个删除或更改,但一次上传所有文件)。

python django django-models django-forms django-file-upload
1个回答
0
投票

看起来你需要从“案例文件”模型到你定义的“案例”模型的一对多外键关系。

models.朋友

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)

然后,您可以添加StackedInline管理表单以将Case Files直接添加到给定的Case。

admin.朋友

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
© www.soinside.com 2019 - 2024. All rights reserved.