Opened 10 years ago

Closed 10 years ago

#12755 closed (wontfix)

Proposal: Add a method to ModelAdmin to return the form instance

Reported by: Igor Sobreira Owned by: nobody
Component: contrib.admin Version: 1.2-alpha
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Sometimes we need dynamic fields in a form, depending on the logged in user or something else. Currently the ModelAdmin class has a get_form() method, that returns a form class to be used in admin. But it would be nice to customize the form instantiation when we are building dynamic forms.

I've attached a patch that adds a get_form_instance() method to ModelAdmin, and it receives the request object. This way we can pass extra parameters to our dynamic form based on some request attributes. For example:

def get_form_instance(self, request, form_class, **kwargs):
    return form_classe(user=request.user, **kwargs)

I don't think it breaks backwards compatibility and it's not a new feature, so probably could be added to 1.2.

Attachments (1)

modeladmin_get_form_instance.patch (2.5 KB) - added by Igor Sobreira 10 years ago.
Add get_form_instance() method to ModelAdmin

Download all attachments as: .zip

Change History (4)

Changed 10 years ago by Igor Sobreira

Add get_form_instance() method to ModelAdmin

comment:1 Changed 10 years ago by Igor Sobreira

Actually it's not needed, not for this example. I could just use functools.partial() in get_form(), like:

def get_form(self, request, obj=None, **kwargs):
    form_class = super(MyModelForm, self).get_form(request, obj=obj, **kwargs)
    return functools.partial(form_class, user=request.user)

comment:2 Changed 10 years ago by James Bennett

milestone: 1.2

This is a feature request, and feature proposal for 1.2 is over. If this ever happens (and I for one wouldn't bet on it), it'll be after 1.2.

comment:3 Changed 10 years ago by Alex Gaynor

Resolution: wontfix
Status: newclosed

Igors has pointed out this isn't necessary.

Note: See TracTickets for help on using tickets.
Back to Top