Django多文件字段

Dav*_*ave 21 django file-upload django-models

是否有可以为django处理多个文件或多个图像的模型字段?或者将ManyToManyField制作成包含图像或文件的单独模型更好?

我需要一个完整的django-admin上传界面解决方案.

MrK*_*Ksn 13

对于2017年及以后的人,Django文档中有一个特殊部分.我的个人解决方案就是这个(在管理员中成功运行):

class ProductImageForm(forms.ModelForm):
    # this will return only first saved image on save()
    image = forms.ImageField(widget=forms.FileInput(attrs={'multiple': True}), required=True)

    class Meta:
        model = ProductImage
        fields = ['image', 'position']

    def save(self, *args, **kwargs):
        # multiple file upload
        # NB: does not respect 'commit' kwarg
        file_list = natsorted(self.files.getlist('{}-image'.format(self.prefix)), key=lambda file: file.name)

        self.instance.image = file_list[0]
        for file in file_list[1:]:
            ProductImage.objects.create(
                product=self.cleaned_data['product'],
                image=file,
                position=self.cleaned_data['position'],
            )

        return super().save(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

  • 这个natsorted来自哪里? (2认同)

Yuj*_*ita 5

没有,没有一个字段知道如何存储Django随附的多个图像。上传的文件作为文件路径字符串存储在模型中,因此本质上是一个CharField知道如何转换为python的文件。

典型的多图像关系被构建为一个单独的图像模型,其中FK指向其相关模型,例如ProductImage -> Product

通过此设置,可以非常轻松地将django admin添加到django admin中Inline

如果您确实GalleryImages是从一个或多个Gallery对象引用的多对多关系,那么M2M字段将很有意义。


Pho*_*beB 5

我不得不将现有系统中的单个文件更改为多个文件,经过一些研究最终使用了这个:https : //github.com/bartTC/django-attachments

如果您想要自定义方法,应该很容易对模型进行子类化。