On Oct 24, 5:14 am, Tim Valenta <tonightslasts...@gmail.com> wrote:
> I've been searching for a while on how to intercept querysets in
> forms, to apply a custom filter to the choices on both foreignkey and
> m2m widgets.  I'm surprised at how there are so many similar questions
> out there, dating back to 2006.

[snip]

> The only solution I've seen has dealt with filtering by User foreign
> key (being that User is available in the request object in views), and
> that's primarily for non-Admin views.

[snip]

> I've been looking at the code for the above noted API method,
> formfield_for_foreignkey, and I really can't see a way to get
> references to an instance of the object being edited.  I would need
> such a reference to successfully override that method and filter my
> queryset on this relationship.

I too spent some time looking at formfield_for_foreignkey, and had no
luck.

You can subclass ModelAdmin, and then limit the objects in the field's
queryset.

** admin.py **

class LocationAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        location = kwargs.get('instance', None)
        if location:
            self.fields['contract'].queryset = Contract.objects.filter
(company=location.company)

class LocationAdmin(admin.ModelAdmin):
    model = Location
    form = LocationAdminForm


I also had to do something similar with Inlines, when I did the same
type of thing.  This is not my exact code, but it is very close, and
suited toward your use case.

Matt.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to