Hi,

I'm trying to limit choices in an admin inline foreign key dropdown. I
have a models.py and admin.py roughly as follows:

# models.py

class Trip(object):
    title = models.CharField(max_length=50)

class Departure(object):
    trip = models.ForeignKey('Trip')
    price_window = models.ForeignKey('PriceWindow', blank=True,
null=True)

class PriceWindow(models.Model):
    trip = models.ForeignKey('Trip')
    title = models.CharField(max_length=50)

# admin.py:

class PriceWindowInline(admin.TabularInline):
    model = PriceWindow
    extra = 1

class DepartureInline(admin.TabularInline):
    model = Departure
    extra = 1

class TripAdmin(admin.ModelAdmin):
    inlines = (PriceWindowInline, DepartureInline)

When I view a Trip in the admin interface, as expected, I get inlines
for Departures and Price Windows. What I would like to do is to
restrict the price window dropdown in the Departure inline to those
price windows which are associated with the trip that is currently
being viewed (the default, of course, is to show all price windows.)

The only way I've found of achieving this is adding the following
method to DepartureInline:

    def formfield_for_dbfield(self, field, **kw):
        if field.name == 'price_window':
            trip_id =
kw['request'].META['PATH_INFO'].strip('/').split('/')[-1]
            trip = Trip.objects.get(pk=trip_id)
            return forms.ModelChoiceField(
                label=u'Price window',
                queryset=PriceWindow.objects.filter(trip=trip)
            )
        else:
            return super(DepartureInline,
self).formfield_for_dbfield(field, **kw)

I don't like this, as it dives into the request and relies on the
structure of the admin URL; it'd be cleaner if I could somehow get a
reference to the Trip that's being edited.

Is there a better way?

Cheers,
Dan

How should I approach this?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@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