我使用Django 1.11.10和python 3.6;我想在管理面板中创建Item
模型,并在同一页面添加多个File
模型,因此我使用TabularInline
。问题出在保存File
模型之前我需要填写其他一些字段,例如上传文件的size
。如果我在课堂上使用admin.ModelAdmin
,那么save_model
会有效,但不适用于admin.TabularInline
。
class Item(models.Model):
title = models.CharField()
class File(models.Model):
name = models.CharField()
size = models.PositiveIntegerField()
file = models.FileField(upload_to='x/')
----
class FileForm(forms.ModelForm):
class Meta:
model = File
fields = ['name', 'file']
def clean(self):
cleaned_data = super().clean()
file = cleaned_data.get('file')
self.size = file.size # file.size shows correct result
class FileInline(admin.TabularInline):
model = File
form = FileForm
def save_formset(self, request, form, formset, change):
logger.info('-- does not get here --')
formset.save_m2m()
def save_model(self, request, obj, form, change):
logger.info('-- does not get here --')
obj.size = form.size
super(FileInline, self).save_model(request, obj, form, change)
class ItemAdmin(admin.ModelAdmin):
inlines = [FileInline]
admin.site.register(Item, ItemAdmin)