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)
4
没有't a single field that knows how to store multiple images shipped with Django. Uploaded files are stored as file path strings in the model, so it'本质上是一个知道如何转换为python的 CharField .
from django.db import models
from filer.fields.image import FilerImageField
from filer.fields.file import FilerFileField
class Company(models.Model):
name = models.CharField(max_length=255)
logo = FilerImageField(null=True, blank=True)
disclaimer = FilerFileField(null=True, blank=True)
Multiple image file fields on the same model in models.py:
注意:需要related_name属性,就像定义外键关系一样 .
from django.db import models
from filer.fields.image import FilerImageField
class Book(models.Model):
title = models.CharField(max_length=255)
cover = FilerImageField(related_name="book_covers")
back = FilerImageField(related_name="book_backs")
4 回答
对于2017年及以后的人来说,有一个special section in Django docs . 我的个人解决方案是这个(在管理员中成功运行):
没有't a single field that knows how to store multiple images shipped with Django. Uploaded files are stored as file path strings in the model, so it'本质上是一个知道如何转换为python的
CharField
.典型的多图像关系构建为单独的图像模型,其中FK指向其相关模型,例如
ProductImage -> Product
.这个设置使得很容易作为
Inline
添加到django管理员 .如果你真的是一个多对多的关系,那么M2M字段就有意义,例如,从一个或多个
Gallery
对象引用GalleryImages
.我不得不从现有系统中的单个文件更改为多个文件,经过一些研究后最终使用此文件:https://github.com/bartTC/django-attachments
如果需要自定义方法,则应该很容易对模型进行子类化 .
FilerFileField and FilerImageField in one model:
它们是django.db.models.ForeignKey的子类,因此适用相同的规则 . 唯一的区别是,不需要声明我们引用的模型(对于FilerFileField,Filer.models.File和FilerImageField的filer.models.Image总是为filer.models.File) .
Simple example models.py:
Multiple image file fields on the same model in models.py:
注意:需要related_name属性,就像定义外键关系一样 .
此答案代码取自django-filer document