django model/modelForm - How to get dynamic choices in choiceField?

前端 未结 2 1222
日久生厌
日久生厌 2020-12-14 23:24

i\'m experimenting with django and the builtin admin interface.

I basically want to have a field that is a drop down in the admin UI. The drop down choices should be

2条回答
  •  情话喂你
    2020-12-14 23:26

    Yay solved. after beating my head all day and going through all sorts of examples by people i got this to work.

    basically i had the right idea with #2. The steps are
    - Create a ModelForm of our model - override the default form field user for a models.CharField. i.e. we want to explcitly say use a choiceField.
    - Then we have to override how the form is instantiated so that we call the thing we want to use to generate our dynamic list of choices
    - then in our ModelAdmin make sure we explicitly tell the admin to use our ModelForm

    class Test1(models.Model):
        test_folder_ddl  = models.CharField(max_length=100)
    
    
    class Test1Form(ModelForm):
        test_folder_ddl = forms.choiceField()
    
        def __init__(self, *args, **kwargs):
           super(Test1Form, self).__init__(*args, **kwargs)
           self.fields['test_folder_ddl'].choices = utility.get_folder_list()
    
    class Test1Admin(admin.ModelAdmin):
        form = Test1Form
    

提交回复
热议问题