Working with extra fields in an Inline form - save_model, save_formset, can't make sense of the difference

后端 未结 2 867
旧时难觅i
旧时难觅i 2021-01-05 14:13

Suppose I am in the usual situation where there\'re extra fields in the many2many relationship:

class Person(models.Model):
    name = models.CharField(max_l         


        
相关标签:
2条回答
  • 2021-01-05 14:25

    As syn points out in his answer, for TabularInline and StackedInline, you have to override the save_formset method inside the ModelAdmin that contains the inlines.

    GroupAdmin(admin.ModelAdmin):
        model = Group
        ....
        inlines = (MembershipInline,)
    
        def save_formset(self, request, form, formset, change):
            instances = formset.save(commit=False)
    
            for instance in instances:
                if isinstance(instance, Member): #Check if it is the correct type of inline
                    if(not instance.author):
                        instance.author = request.user
                    else:
                        instance.modified_by = request.user            
                    instance.save()
    
    0 讨论(0)
  • 2021-01-05 14:29

    I just hit this same problem, and it seems the solution is that for both save_formset and save_model with inlines, they are not called. Instead you must implement it in the formset which is being called which is the parent e.g.

    model = Group
        ....
        inlines = (MembershipInline,)
    
        def save_formset(self, request, form, formset, change):
            instances = formset.save(commit=False)
    
            for instance in instances:
                # Here an instance is a MembershipInline formset NOT a group...
                instance.someunsetfield = something
    
                # I think you are creating new objects, so you could do it here.
                instance.save()
    
    0 讨论(0)
提交回复
热议问题