[Answer]-How to set models choices dynamicly in Django

1👍

You don’t need two separate fields. The field just holds the data, you instead need to filter what choices the user is presented with in their form. If you are using the django admin for example, you can do something like (untested)

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, *kwargs):
         super(MyModel, self).__init__(args, kwargs)
         if self.fields['project'].foo == "bar":
             self.fields['owner'].choices = ((0, "X"), (1, "Y"),...)
         else:
             self.fields['owner'].choices = ((0, "A"), (1, "B"),...)

    class Meta:
         model = MyModel

admin.py

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

Leave a comment