Code

Opened 7 years ago

Closed 5 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@…, apollo13, mwdiers 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)

See discussion in comments.

Attachments (11)

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

Download all attachments as: .zip

Change History (44)

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

the patch

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

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

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

  • Triage Stage changed from Unreviewed to Design decision needed

comment:3 Changed 7 years ago by adrian

  • Version changed from new-admin to SVN

comment:4 Changed 7 years ago by adrian

  • Version changed from SVN to newforms-admin

comment:5 Changed 7 years ago by adrian

  • Description modified (diff)
  • Summary changed from Customs filters for related keys in the admin (newforms-admin) to ModelAdmin should allow for overriding of ForeignKey/ManyToMany options
  • Triage Stage changed from Design decision needed to Accepted

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

  • Cc brosner@… added

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

new patch (cleaner ?)

comment:8 Changed 7 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 7 years ago by Baptiste <baptiste.goupil@…>

oops, fixed a little error

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

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

comment:9 Changed 7 years ago by anonymous

  • Cc django@… added

comment:10 Changed 7 years ago by anonymous

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

comment:11 Changed 7 years ago by ext

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 7 years ago by ext

Patch updated to work with version 6426

comment:12 Changed 7 years ago by ext

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 7 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 follow-ups: Changed 7 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 7 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 7 years ago by ext

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 6 years ago by mikeblake

Updated to revision 8151

comment:17 in reply to: ↑ description ; follow-up: Changed 6 years ago by mikeblake

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 6 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 6 years ago by ikse hefem

tentative feature documentation

Changed 6 years ago by ikse hefem

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

comment:19 Changed 6 years ago by ikse hefem

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

comment:20 Changed 6 years ago by apollo13

  • Cc apollo13 added; django@… removed

comment:21 Changed 6 years ago by anonymous

  • Owner changed from nobody to anonymous
  • Status changed from new to assigned

comment:22 Changed 6 years ago by anonymous

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

comment:23 Changed 6 years ago by anonymous

  • Needs documentation unset
  • Needs tests unset
  • Resolution fixed deleted
  • Status changed from closed to reopened
  • Triage Stage changed from Accepted to Ready for checkin

comment:24 Changed 6 years ago by apollo13

  • Owner changed from anonymous to nobody
  • Status changed from reopened to new
  • Triage Stage changed from Ready for checkin to Someday/Maybe

Changed 6 years ago by Xniver

updated, works with revision 8502

Changed 6 years ago by Xniver

sorry, forgot to change extension

comment:25 Changed 6 years ago by anonymous

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

comment:26 Changed 6 years ago by anonymous

  • Resolution fixed deleted
  • Status changed from closed to reopened

comment:27 Changed 6 years ago by anonymous

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

comment:28 Changed 6 years ago by julien

  • Resolution fixed deleted
  • Status changed from closed to reopened

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

comment:29 Changed 6 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 6 years ago by mwdiers

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

comment:30 Changed 6 years ago by mwdiers

  • Cc mwdiers added

comment:31 Changed 6 years ago by mwdiers

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 6 years ago by mwdiers

  • Needs tests set
  • Patch needs improvement set
  • Triage Stage changed from Someday/Maybe to Design 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 5 years ago by jacob

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

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

Add Comment

Modify Ticket

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


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

 
Note: See TracTickets for help on using tickets.