how to modify choices on admin pages - django

后端 未结 4 781
猫巷女王i
猫巷女王i 2020-12-15 11:27

I have a model that has a field named \"state\":

class Foo(models.Model):
    ...
    state = models.IntegerField(choices = STATES)
    ...

4条回答
  •  别那么骄傲
    2020-12-15 12:11

    You need to use a custom ModelForm in the ModelAdmin class for that model. In the custom ModelForm's __init__ method, you can dynamically set the choices for that field:

    class FooForm(forms.ModelForm):
        class Meta:
            model = Foo
    
        def __init__(self, *args, **kwargs):
            super(FooForm, self).__init__(*args, **kwargs)
            current_state = self.instance.state
            ...construct available_choices based on current state...
            self.fields['state'].choices = available_choices
    

    You'd use it like this:

    class FooAdmin(admin.ModelAdmin):
        form = FooForm
    

提交回复
热议问题