Opened 17 years ago

Closed 15 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: no UI/UX: no

Description (last modified by Adrian Holovaty)

See discussion in comments.

Attachments (11)

customfilters.diff (7.8 KB ) - added by Baptiste <baptiste.goupil@…> 17 years ago.
the patch
diff-dynamic.diff (7.7 KB ) - added by Baptiste <baptiste.goupil@…> 17 years ago.
new patch (cleaner ?)
diff-dynamic.2.diff (7.6 KB ) - added by Baptiste <baptiste.goupil@…> 17 years ago.
oops, fixed a little error
diff-dynamic.3.diff (8.6 KB ) - added by Baptiste <baptiste.goupil@…> 17 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 16 years ago.
Patch updated to work with version 6426
dynamic_related_3987.2.diff (4.6 KB ) - added by Django Trac 16 years ago.
Updated to revision 8151
doc_diff.txt (1.2 KB ) - added by ikse hefem 16 years ago.
tentative feature documentation
doc.diff (1.3 KB ) - added by ikse hefem 16 years ago.
New patch (sorry, fisrt try) , forget/delete the preceding one if possible
diff.txt (4.3 KB ) - added by Xniver 16 years ago.
updated, works with revision 8502
dynamic.diff (4.3 KB ) - added by Xniver 16 years ago.
sorry, forgot to change extension
dynamic_choice_9014.diff (4.4 KB ) - added by Martin Diers 16 years ago.
Updated patch to rev 9014. This will work with 1.0 also.

Download all attachments as: .zip

Change History (44)

by Baptiste <baptiste.goupil@…>, 17 years ago

Attachment: customfilters.diff added

the patch

comment:2 by Simon G. <dev@…>, 17 years ago

Triage Stage: UnreviewedDesign decision needed

comment:3 by Adrian Holovaty, 17 years ago

Version: new-adminSVN

comment:4 by Adrian Holovaty, 17 years ago

Version: SVNnewforms-admin

comment:5 by Adrian Holovaty, 17 years ago

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 by Baptiste <baptiste.goupil@…>, 17 years ago

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 by Brian Rosner <brosner@…>, 17 years ago

Cc: brosner@… added

by Baptiste <baptiste.goupil@…>, 17 years ago

Attachment: diff-dynamic.diff added

new patch (cleaner ?)

comment:8 by Baptiste <baptiste.goupil@…>, 17 years ago

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)            

by Baptiste <baptiste.goupil@…>, 17 years ago

Attachment: diff-dynamic.2.diff added

oops, fixed a little error

by Baptiste <baptiste.goupil@…>, 17 years ago

Attachment: diff-dynamic.3.diff added

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

comment:9 by anonymous, 17 years ago

Cc: django@… added

comment:10 by anonymous, 17 years ago

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

comment:11 by Jakub Wiśniowski, 16 years ago

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".

by Jakub Wiśniowski, 16 years ago

Attachment: dynamic_related_3987.diff added

Patch updated to work with version 6426

comment:12 by Jakub Wiśniowski, 16 years ago

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 by Karen Tracey <kmtracey@…>, 16 years ago

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 by Baptiste, 16 years ago

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.

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

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.

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

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!

by Django Trac, 16 years ago

Attachment: dynamic_related_3987.2.diff added

Updated to revision 8151

in reply to:  description ; comment:17 by Django Trac, 16 years ago

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.

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

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.

by ikse hefem, 16 years ago

Attachment: doc_diff.txt added

tentative feature documentation

by ikse hefem, 16 years ago

Attachment: doc.diff added

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

comment:19 by ikse hefem, 16 years ago

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

comment:20 by Florian Apolloner, 16 years ago

Cc: Florian Apolloner added; django@… removed

comment:21 by anonymous, 16 years ago

Owner: changed from nobody to anonymous
Status: newassigned

comment:22 by anonymous, 16 years ago

Resolution: fixed
Status: assignedclosed

comment:23 by anonymous, 16 years ago

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

comment:24 by Florian Apolloner, 16 years ago

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

by Xniver, 16 years ago

Attachment: diff.txt added

updated, works with revision 8502

by Xniver, 16 years ago

Attachment: dynamic.diff added

sorry, forgot to change extension

comment:25 by anonymous, 16 years ago

Resolution: fixed
Status: newclosed

comment:26 by anonymous, 16 years ago

Resolution: fixed
Status: closedreopened

comment:27 by anonymous, 16 years ago

Resolution: fixed
Status: reopenedclosed

comment:28 by Julien Phalip, 16 years ago

Resolution: fixed
Status: closedreopened

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

comment:29 by anonymous, 16 years ago

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.

by Martin Diers, 16 years ago

Attachment: dynamic_choice_9014.diff added

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

comment:30 by Martin Diers, 16 years ago

Cc: Martin Diers added

comment:31 by Martin Diers, 16 years ago

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 by Martin Diers, 16 years ago

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 by Jacob, 15 years ago

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