Django admin choice field

前端 未结 7 1665
日久生厌
日久生厌 2020-12-18 22:48

I have a model that has a CharField and in the admin I want to add choices to the widget. The reason for this is I\'m using a proxy model and there are a bunch of models tha

7条回答
  •  半阙折子戏
    2020-12-18 22:56

    You need to override the form the ModelAdmin is going to use:

    class MyForm(forms.ModelForm):
        stuff = forms.CharField('Stuff', max_length=255, choices=MY_CHOICES, default=None)
    
        class Meta:
            model = MyModel
            fields = ('stuff', 'other_field', 'another_field')
    
    
    class MyModelAdmin(admin.ModelAdmin):
        fields = ('stuff',)
        list_display = ('stuff',)
        form = MyForm
    

    If you need your choices to be dynamic, maybe you could do something similar to:

    class MyForm(forms.ModelForm):
        stuff = forms.CharField('Stuff', max_length=255, choices=MY_CHOICES, default=None)
    
        def __init__(self, stuff_choices=(), *args, **kwargs):
            # receive a tupple/list for custom choices
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields['stuff'].choices = stuff_choices
    

    and in your ModelAdmin's __init__ define what MY_CHOICES is going to be and assign the form instance there instead:

    Good luck! :)

提交回复
热议问题