我有以下模型表格:
class ImageModelForm(FilesForm):
class Meta:
model = Image
fields = ['image', 'order_id']
class FilesForm(forms.ModelForm):
def save(self, commit=True):
obj = super().save(commit=False)
for field, value in self.fields.items():
if isinstance(value, forms.FileField) and obj:
obj.filename = truncate_filename(self.cleaned_data[field].name.lower())
obj.file_type = self.cleaned_data[field].content_type.lower()
# commit is False usually in Admin - check to work also in Admin
if commit:
obj.save()
return obj
class Image(FileAttributesModel):
item = models.ForeignKey('Item', on_delete=models.CASCADE)
image = models.ImageField(upload_to=file_upload_to, max_length=500)
order_id = models.SmallIntegerField(default=0)
class FileAttributesModel(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
file_type = models.CharField(max_length=255, blank=True, null=True)
class Meta:
abstract = True
如果我从表单中删除了'order_id'或不更改它的值,则它正常工作,否则得到:
'ImageFieldFile' object has no attribute 'content_type'
在回溯中,使用保存方法跟踪错误:
obj.file_type = self.cleaned_data[field].content_type.lower()
在两种情况下,该字段均为:图片
但是,没有值更改为order_id
{'file': <_io.BytesIO object at 0x0000000005F7CE08>, '_name': 'broad-range.png', 'size': 76310, 'content_type': 'image/png', 'charset': None, 'content_type_extra': {}, 'field_name': 'image-1-image', 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGB size=1000x468 at 0x64B8A20>}
更改了order_id:
{'_file': None, 'name': /images/broad-range.png', 'instance': <Image: images/06_axft.jpg>, 'field': <django.db.models.fields.files.ImageField: image>, 'storage': <django.core.files.storage.DefaultStorage object at 0x00000000038FEDD8>, '_committed': True}