Django admin:如何在TabularInline中保存_model()?

时间:2018-02-13 14:07:35

标签: python django django-admin

我使用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)

1 个答案:

答案 0 :(得分:0)

查看save_related

我相信这就是你需要的东西