[Answered ]-Best way to implement depedent choices in Django models

2👍

class CarAd(models.Model):
    MAKE_HONDA = 0
    MAKE_TOYOTA = 1
    MAKES = ((MAKE_HONDA, 'Honda'),
             (MAKE_TOYOTA, 'Toyota'),)

    MODELS = { MAKE_HONDA: ('Civic', 'City',),
               MAKE_TOYOTA: ('Corolla', 'Prius',)
             }

    make = models.IntegerField(choices=MAKES)

# Django Form
class CarAdForm(forms.Form):
    make = forms.ChoiceField(choices=CarAd.MAKES)

    def __init__(self, *args, **kwargs):
        super(forms.Form, self).__init__(*args, **kwargs)

        # Car make
        make = args[0]['make']
        models = CarAd.MODELS[make]
        self.fields['models'] = forms.ChoiceField(choices=models)

Leave a comment