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

10👍

This is the answer, it is brilliant: https://github.com/digi604/django-smart-selects

👤Brian

5👍

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 forms

from models import location_unit, location, project_unit

class 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 admin

from models import location_unit
from forms import LocationUnitForm

class LocationUnitAdmin(admin.ModelAdmin):
    form = LocationUnitForm

admin.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.)

Leave a comment