Skip to main content
 首页 » 编程设计

python之Django 管理员在清理表单时编辑内联对象

2025年05月04日34qq78292959

我有以下模型:

class ProjectBudget(models.Model): 

它有一个表单和内联:

class ProjectBudgetAdmin(admin.ModelAdmin):   
    form = ProjectBudgetForm 
    inlines= [ProjectSpentsInline] 
 
class ProjectSpentsInline(admin.TabularInline): 
    model = ProjectSpents 

在表单上我有一个字段file。从这个文件我想填充内联对象 ProjectSpents 值:

class ProjectBudgetForm(ModelForm): 
    file  = forms.FileField 
 
    def clean_file(self): 
        parse file then populate inline model objects ProjectSpents.... 

问题是我想从 clean_file 编辑 ProjectSpents 的内联值,但是有一个问题,因为查询集在 clean_file 之前已经填满,而新的内联值还没有 秀翼。也许还有其他解决方案?

请您参考如下方法:

尝试覆盖模型管理方法 save_formset .您可以遍历 formset 实例以删除现有的内联,然后访问 form.cleaned_data['file'] 并创建新的相关实例。