In django, how to limit choices of a foreignfield based on another field in the same model? In django, how to limit choices of a foreignfield based on another field in the same model? django django

In django, how to limit choices of a foreignfield based on another field in the same model?


Your formfield_for_foreignkey looks like it might be a good direction, but you have to realize that the ModelAdmin (self) won't give you a specific instance. You'll have to derive that from the request (possibly a combination of django.core.urlresolvers.resolve and request.path)


If you only want this functionality in the admin (and not model validation in general), you can use a custom form with the model admin class:

forms.py:

from django import formsfrom models import location_unit, location, project_unitclass LocationUnitForm(forms.ModelForm):    class Meta:        model = location_unit    def __init__(self, *args, **kwargs):        inst = kwargs.get('instance')        super(LocationUnitForm, self).__init__(*args, **kwargs)        if inst:            self.fields['location'].queryset = location.objects.filter(project=inst.project)            self.fields['unit'].queryset = project_unit.objects.filter(project=inst.project)

admin.py:

from django.contrib import adminfrom models import location_unitfrom forms import LocationUnitFormclass LocationUnitAdmin(admin.ModelAdmin):    form = LocationUnitFormadmin.site.register(location_unit, LocationUnitAdmin)

(Just wrote these on the fly with no testing, so no guarantee they'll work, but it should be close.)