#21528: improve Django Doc with an example for formfield_for_foreignkey 
accessing
parent ID
--------------------------------------+------------------------------------
     Reporter:  anonymous             |                    Owner:  nobody
         Type:  Cleanup/optimization  |                   Status:  new
    Component:  Documentation         |                  Version:  master
     Severity:  Normal                |               Resolution:
     Keywords:                        |             Triage Stage:  Accepted
    Has patch:  1                     |      Needs documentation:  0
  Needs tests:  0                     |  Patch needs improvement:  1
Easy pickings:  0                     |                    UI/UX:  0
--------------------------------------+------------------------------------

Comment (by Tobias Kunze):

 For reference, the blog post referred to in the original issue can be
 found
 [https://web.archive.org/web/20130403060642/http://www.stereoplex.com/blog
 /filtering-dropdown-lists-in-the-django-admin/ on the web archive], and
 the relevant code reads like this:


 {{{
 class MountaineeringInfoInline(admin.TabularInline):
     model = MountaineeringInfo
     formset = MountaineeringInfoInlineFormset

     def formfield_for_dbfield(self, field, **kwargs):
         if field.name == 'area':
             # Note - get_object hasn't been defined yet
             parent_trip = self.get_object(kwargs['request'], Trip)
             contained_areas =
 Area.objects.filter(area__contains=parent_trip.area.area)
             return forms.ModelChoiceField(queryset=contained_areas)
         return super(MountaineeringInfoInline,
 self).formfield_for_dbfield(field, **kwargs)

     def get_object(self, request, model):
         object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
         try:
             object_id = int(object_id)
         except ValueError:
             return None
         return model.objects.get(pk=object_id)
 }}}

 At least mentioning `formfield_for_dbfield` in the docs at all, anywhere,
 sounds like a good idea to me, regardless of the specifics on how to get
 the current pk or instance.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/21528#comment:5>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/067.df0e2dad3d59f15e93b56ed1c9217099%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to