Changes between Version 47 and Version 48 of NewformsHOWTO

09/13/2008 04:20:09 PM (10 years ago)
Martin Diers



  • NewformsHOWTO

    v47 v48  
    699 == Q: How do I filter the ChoiceField of an InlineAdmin depending on attributes of the parent object? ==
    700 A: This is currently worked on. See ticket #3987
     699== Q: How do I filter the ChoiceField based upon attributes of the current ModelAdmin instance? ==
     700A: This is currently worked on in ticket #3987. However, this patch is not likely to be implemented, as it is not
     701backward compatible.
     703There is another way that works with 1.0 just fine. Override the _ _ call _ _  method to add the
     704request object to the current ModelAdmin instance. At that point, you can reference the request object inside formfield_for_dbfield,
     705and retrieve the current Model instance, which you may then use to filter a ChoiceField based upon the current values
     706in the Model. The following example filters a ChoiceField based upon attributes of the the current Model instance. The same thing may
     707be done within an InlineAdmin, retrieving the parent object instance, and using it to filter the ChoiceField on the InlineAdmin instances:
     710class SiteAdmin(ModelAdmin):
     711    def __call__(self, request, url):
     712        #Add in the request object, so that it may be referenced
     713        #later in the formfield_for_dbfield function.
     714        self.request = request
     715        return super(SiteAdmin, self).__call__(request, url)
     717    def get_form(self, request, obj=None):
     718        form = super(SiteAdmin, self).get_form(request, obj)
     719        #print form
     720        return form
     722    def formfield_for_dbfield(self, db_field, **kwargs):
     723        field = super(SiteAdmin, self).formfield_for_dbfield(db_field, **kwargs) # Get the default field
     724        if == 'home_page':
     725            #Add the null object
     726            my_choices = [('', '---------')]
     727            #Grab the current site id from the URL.
     728            my_choices.extend(Page.objects.filter(site=self.request.META['PATH_INFO'].split('/')[-2]).values_list('id','name'))
     729            print my_choices
     730            field.choices = my_choices
     731        return field
Back to Top