Opened 9 years ago

Closed 8 years ago

#3987 closed (fixed)

ModelAdmin should allow for overriding of ForeignKey/ManyToMany options

Reported by: Baptiste <baptiste.goupil@…> Owned by: nobody
Component: contrib.admin Version: newforms-admin
Severity: Keywords: nfa-someday
Cc: brosner@…, Florian Apolloner, Martin Diers Triage Stage: Design decision needed
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: yes
Easy pickings: UI/UX:

Description (last modified by Adrian Holovaty)

See discussion in comments.

Attachments (11)

customfilters.diff (7.8 KB) - added by Baptiste <baptiste.goupil@…> 9 years ago.
the patch
diff-dynamic.diff (7.7 KB) - added by Baptiste <baptiste.goupil@…> 9 years ago.
new patch (cleaner ?)
diff-dynamic.2.diff (7.6 KB) - added by Baptiste <baptiste.goupil@…> 9 years ago.
oops, fixed a little error
diff-dynamic.3.diff (8.6 KB) - added by Baptiste <baptiste.goupil@…> 9 years ago.
security fix : the choice of an item not in the list of choices must fail
dynamic_related_3987.diff (6.4 KB) - added by Jakub Wiśniowski 9 years ago.
Patch updated to work with version 6426
dynamic_related_3987.2.diff (4.6 KB) - added by Django Trac 8 years ago.
Updated to revision 8151
doc_diff.txt (1.2 KB) - added by ikse hefem 8 years ago.
tentative feature documentation
doc.diff (1.3 KB) - added by ikse hefem 8 years ago.
New patch (sorry, fisrt try) , forget/delete the preceding one if possible
diff.txt (4.3 KB) - added by Xniver 8 years ago.
updated, works with revision 8502
dynamic.diff (4.3 KB) - added by Xniver 8 years ago.
sorry, forgot to change extension
dynamic_choice_9014.diff (4.4 KB) - added by Martin Diers 8 years ago.
Updated patch to rev 9014. This will work with 1.0 also.

Download all attachments as: .zip

Change History (44)

Changed 9 years ago by Baptiste <baptiste.goupil@…>

Attachment: customfilters.diff added

the patch

comment:1 Changed 9 years ago by Baptiste <baptiste.goupil@…>

Has patch: set
Needs documentation: unset
Needs tests: unset
Patch needs improvement: set

comment:2 Changed 9 years ago by Simon G. <dev@…>

Triage Stage: UnreviewedDesign decision needed

comment:3 Changed 9 years ago by Adrian Holovaty

Version: new-adminSVN

comment:4 Changed 9 years ago by Adrian Holovaty

Version: SVNnewforms-admin

comment:5 Changed 9 years ago by Adrian Holovaty

Description: modified (diff)
Summary: Customs filters for related keys in the admin (newforms-admin)ModelAdmin should allow for overriding of ForeignKey/ManyToMany options
Triage Stage: Design decision neededAccepted

I like the idea, but the implementation is a bit brittle. What about adding method hooks on ModelAdmin that would allow you to specify the options for a given ForeignKey field? These methods could get passed the request object, so you could do per-user options. Something like this:

# Model

class Book(models.Model):
    title = models.CharField(maxlength=100)
    author = models.ForeignKey(Author)

# Admin

class BookAdmin(ModelAdmin):
    def dynamic_author_choices(self, request, book):
        # Default implementation:
        # return book.author_set.all()
        return book.author_set.filter(use_in_admin=True)

comment:6 Changed 9 years ago by Baptiste <baptiste.goupil@…>

If dynamic_field_choices() is automatically called for every field when admin is displayed, that would be great, but should also work for ManyToManyField.

comment:7 Changed 9 years ago by Brian Rosner <brosner@…>

Cc: brosner@… added

Changed 9 years ago by Baptiste <baptiste.goupil@…>

Attachment: diff-dynamic.diff added

new patch (cleaner ?)

comment:8 Changed 9 years ago by Baptiste <baptiste.goupil@…>

Patch needs improvement: unset

Okay, here is a new patch that I hope cleaner.

It works almost like Adrian suggested it :

# Model

class Book(models.Model):
    title = models.CharField(maxlength=100)
    author = models.ForeignKey(Author)

# Admin

class BookAdmin(ModelAdmin):
    def dynamic_author_choices(self, request, model):
        # Default implementation:
        # return book.author_set.all()
        return model.objects.filter(use_in_admin=True)

And also allows:

class BookAdmin(ModelAdmin):
    def dynamic_author_choices(self, request, model):
        if request.user.is_superuser:
            return model.objects.all()
        return model.objects.filter(use_in_admin=True)            

Changed 9 years ago by Baptiste <baptiste.goupil@…>

Attachment: diff-dynamic.2.diff added

oops, fixed a little error

Changed 9 years ago by Baptiste <baptiste.goupil@…>

Attachment: diff-dynamic.3.diff added

security fix : the choice of an item not in the list of choices must fail

comment:9 Changed 9 years ago by anonymous

Cc: django@… added

comment:10 Changed 9 years ago by anonymous

I am +1 for this patch. This is really a useful addition.

comment:11 Changed 9 years ago by Jakub Wiśniowski

I attached an updated version of patch. It now works with revision: 6426.

A little change I did to the patch is removal of all occurences of:

defaults = {'form_class': forms.ModelChoiceField} 
#To prevent an useless query
if not 'queryset' in kwargs: 
   defaults['queryset'] = self.rel.to._default_manager.all()

in favour of original code:

defaults = {'form_class': forms.ModelChoiceField, 'queryset': self.rel.to._default_manager.all()} 

The reason is that QuerySets are lazy so there is no "useless query".

Changed 9 years ago by Jakub Wiśniowski

Attachment: dynamic_related_3987.diff added

Patch updated to work with version 6426

comment:12 Changed 9 years ago by Jakub Wiśniowski

I replaced the previous version of the patch, because it had a small bug. I did simple replacement in line 203 of models.py (s/value/val/)

comment:13 Changed 9 years ago by Karen Tracey <kmtracey@…>

Keywords: nfa-someday added
Needs documentation: set
Needs tests: set

New function so it shouldn't block newforms-admin merge. Also it needs docs and tests, I think.

comment:14 Changed 9 years ago by Baptiste

It doesn't block the merge since it is a newforms-admin patch.

But I am not going to write doc and tests since I haven't had any feedback about this and I have no idea if it has a chance to be accepted! If someone said it could be accepted, I would do it, sure.

comment:15 in reply to:  14 Changed 9 years ago by Karen Tracey <kmtracey@…>

Replying to Baptiste:

But I am not going to write doc and tests since I haven't had any feedback about this and I have no idea if it has a chance to be accepted! If someone said it could be accepted, I would do it, sure.

Triage stage is Accepted, and you've updated the patch to be in line with Adrian's suggestion, so I was thinking it had been accepted. I believe a complete package is more likely than just a code patch to get the review needed to move on to ready for checkin.

comment:16 in reply to:  14 Changed 9 years ago by Jakub Wiśniowski

Replying to Baptiste:

But I am not going to write doc and tests since I haven't had any feedback about this and I have no idea if it has a chance to be accepted! If someone said it could be accepted, I would do it, sure.

It should be accepted. Enough? ;) Hey! This patch is very important to me. It would be great to have it merged with the trunk!

Changed 8 years ago by Django Trac

Attachment: dynamic_related_3987.2.diff added

Updated to revision 8151

comment:17 in reply to:  description ; Changed 8 years ago by Django Trac

Replying to Baptiste <baptiste.goupil@gmail.com>:

See discussion in comments.

I think I have upgraded the patch to work with latest SVN copy. First time looking into the code!

Would greatly appreciate it if this patch was included in 1.0 as it's an incredibly handy feature.

comment:18 in reply to:  17 Changed 8 years ago by Karen Tracey <kmtracey@…>

Replying to mikeblake:

Would greatly appreciate it if this patch was included in 1.0 as it's an incredibly handy feature.

It was accepted by Adrian and seems to have multiple people interested in it, however it's got no docs nor tests. That's probably preventing it from moving along in the process.

Changed 8 years ago by ikse hefem

Attachment: doc_diff.txt added

tentative feature documentation

Changed 8 years ago by ikse hefem

Attachment: doc.diff added

New patch (sorry, fisrt try) , forget/delete the preceding one if possible

comment:19 Changed 8 years ago by ikse hefem

First proposal for a documentation.
Forget the first patch, totally wrong.

comment:20 Changed 8 years ago by Florian Apolloner

Cc: Florian Apolloner added; django@… removed

comment:21 Changed 8 years ago by anonymous

Owner: changed from nobody to anonymous
Status: newassigned

comment:22 Changed 8 years ago by anonymous

Resolution: fixed
Status: assignedclosed

comment:23 Changed 8 years ago by anonymous

Needs documentation: unset
Needs tests: unset
Resolution: fixed
Status: closedreopened
Triage Stage: AcceptedReady for checkin

comment:24 Changed 8 years ago by Florian Apolloner

Owner: changed from anonymous to nobody
Status: reopenednew
Triage Stage: Ready for checkinSomeday/Maybe

Changed 8 years ago by Xniver

Attachment: diff.txt added

updated, works with revision 8502

Changed 8 years ago by Xniver

Attachment: dynamic.diff added

sorry, forgot to change extension

comment:25 Changed 8 years ago by anonymous

Resolution: fixed
Status: newclosed

comment:26 Changed 8 years ago by anonymous

Resolution: fixed
Status: closedreopened

comment:27 Changed 8 years ago by anonymous

Resolution: fixed
Status: reopenedclosed

comment:28 Changed 8 years ago by Julien Phalip

Resolution: fixed
Status: closedreopened

Looks like Mr Anonymous is having a bit of fun here...

comment:29 Changed 8 years ago by anonymous

I'ld like to show in model A list_filter model B fields that have a ForeignKey to model A.
I've applied dynamic_related_3987.2.diff to django svn trunk.
I've add a method get_b() to the A admin class ("class AAdmin(admin.ModelAdmin):") that returns a.b_set.all(), but I don't know how I've to include it in list_filter. I've put "list_filter = (...,'get_b')" but get the error:

Error while importing URLconf 'myapp.urls': `AAdmin.list_filter[9]` refers to field `get_b` that is missing from model `A`.

What should be solve the error?

Thanks in advance.

Changed 8 years ago by Martin Diers

Attachment: dynamic_choice_9014.diff added

Updated patch to rev 9014. This will work with 1.0 also.

comment:30 Changed 8 years ago by Martin Diers

Cc: Martin Diers added

comment:31 Changed 8 years ago by Martin Diers

There is a serious problem with this patch. It changes the formfield_for_dbfield method of ModelAdmin, requiring a request object to passed in as a positional argument. This method is not in the docs, but it is commonly overridden, and represents a significant change to the API for the Admin.

There is a way to do what this patch does on 1.0, without any patching:

class SiteAdmin(ModelAdmin):
    def __call__(self, request, url):
        #Add in the request object, so that it may be referenced
        #later in the formfield_for_dbfield function.
        self.request = request
        return super(SiteAdmin, self).__call__(request, url)
    
    def get_form(self, request, obj=None):
        form = super(SiteAdmin, self).get_form(request, obj)
        #print form
        return form
            
    def formfield_for_dbfield(self, db_field, **kwargs):
        field = super(SiteAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Get the default field
        if db_field.name == 'home_page': 
            #Add the null object
            my_choices = [('', '---------')]
            #Grab the current site id from the URL.
            my_choices.extend(Page.objects.filter(site=self.request.META['PATH_INFO'].split('/')[-2]).values_list('id','name'))
            print my_choices
            field.choices = my_choices
        return field

The trick is the override of _ _call_ _, adding the request object as an attribute of the instance. Once you have this, you can do pretty much anything you need in the formfield_for_dbfield override. Granted, this is not very elegant. But it works in 1.0, and our users are already accustomed to overriding formfield_for_dbfield to make custom form tweaks.

comment:32 Changed 8 years ago by Martin Diers

Needs tests: set
Patch needs improvement: set
Triage Stage: Someday/MaybeDesign decision needed

Sorry. Had some superfluous code in that example. Updated version for reference:

class SiteAdmin(ModelAdmin):
    def __call__(self, request, url):
        #Add in the request object, so that it may be referenced
        #later in the formfield_for_dbfield function.
        self.request = request
        return super(SiteAdmin, self).__call__(request, url)
    
    def formfield_for_dbfield(self, db_field, **kwargs):
        field = super(SiteAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Get the default field
        if db_field.name == 'home_page': 
            #Add the null object
            my_choices = [('', '---------')]
            #Grab the current site id from the URL.
            my_choices.extend(Page.objects.filter(site=self.request.META['PATH_INFO'].split('/')[-2]).values_list('id','name'))
            print my_choices
            field.choices = my_choices
        return field

comment:33 Changed 8 years ago by Jacob

Resolution: fixed
Status: reopenedclosed

(In [9760]) Cleaned up and refactored ModelAdmin.formfield_for_dbfield:

  • The new method uses an admin configuration option (formfield_overrides); this makes custom admin widgets especially easy.
  • Refactored what was left of formfield_for_dbfield into a handful of smaller methods so that it's easier to hook in and return custom fields where needed.
  • These formfield_for_* methods now pass around request so that you can easily modify fields based on request (as in #3987).

Fixes #8306, #3987, #9148.

Thanks to James Bennet for the original patch; Alex Gaynor and Brian Rosner also contributed.

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