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

标签 python django django-models django-forms django-file-upload

我想在 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)

最终目标

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

最佳答案

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

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)

然后,您可以添加 StackedInline 管理表单以将案例文件直接添加到给定案例。

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

关于python - 如何从 Django 管理上传多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543232/

相关文章:

django - 使用 Django 检查内部 IP

python - 使用字符串中的日期时间创建 Django 模型

python - Django 通用外键 : accessor clash when 2 models have same related_name

python - Django 不允许我保存 User 对象

python - 模板中的 sart 函数

python - 基于多种模型的Django Form

python - 如何制作一个迭代超过 1500 万条记录的 for 循环,节省空间?

python - 用 Python 播放音频文件

python - 获取字符串的每个组合

Python 扩展 : using different compiler flags for a C parts and C++ parts