Opened 3 years ago

Closed 3 years ago

#15820 closed Bug (fixed)

inline admin formset uses incorrect form

Reported by: shanyu Owned by: nobody
Component: contrib.admin Version: 1.2
Severity: Normal Keywords: inlinemodeladmin, inlines
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I have the (somewhat simplified) following code:

def create_foo_form(baz):
    class FooForm(forms.ModelForm):
       def __init__(self, *args, **kwargs):
           print "Initializing a FooForm object"
           # Init stuff here
    return FooForm

class FooInline(admin.TabularInline):
    model = Foo

    def get_formset(self, request, obj=None, **kwargs):
        if obj:
            kwargs['form'] = create_foo_form(obj)
        return super(FooInline, self).get_formset(request, obj, **kwargs)

class BazAdmin(admin.ModelAdmin):
    inlines = [FooInline,]

The problem is that the inline formset always uses my custom FooForm, though the code above clearly chooses it only if obj is not None (Otherwise the default self.form should be used).

The following code is get_fieldsets method of InlineModelAdmin.

    def get_fieldsets(self, request, obj=None):
        if self.declared_fieldsets:
            return self.declared_fieldsets
        form = self.get_formset(request).form
        fields = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))
        return [(None, {'fields': fields})]

The line "form = self.get_formset(request).form" calls get_formset method without providing the argument "obj". That results in using an incorrect form in this case. I guess the correct form would be "form = self.get_formset(request, obj).form".

Attachments (1)

15820.inlinemodeladmin-get_fieldsets.diff (2.4 KB) - added by julien 3 years ago.
Fix + tests

Download all attachments as: .zip

Change History (5)

comment:1 Changed 3 years ago by jacob

  • Easy pickings unset
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

Changed 3 years ago by julien

Fix + tests

comment:2 Changed 3 years ago by julien

  • Has patch set

comment:3 Changed 3 years ago by prestontimmons

  • Triage Stage changed from Accepted to Ready for checkin
  • UI/UX unset

I applied and reviewed this patch for r16452. It looks good. Marking as RFC.

comment:4 Changed 3 years ago by jezdez

  • Resolution set to fixed
  • Status changed from new to closed

In [16497]:

Fixed #15820 -- Fixed the use of the InlineAdmin's get_formset method by actually passing in the obj. Thanks, Julien Phalip.

Add Comment

Modify Ticket

Change Properties
<Author field>
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.