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

前端 未结 2 1217
日久生厌
日久生厌 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:25

    I use a generator:

    see git://gist.github.com/1118279.git

        import pysvn
    
        class SVNChoices(DynamicChoice):
            """
            Generate a choice from somes files in a svn repo
            """"
            SVNPATH = 'http://xxxxx.com/svn/project/trunk/choices/'
            def generate(self):
                def get_login( realm, username, may_save ):
                    return True, 'XXX', 'xxxxx', True
                client = pysvn.Client()
                client.callback_get_login = get_login
                return [os.path.basename(sql[0].repos_path) for sql in client.list(self.SVNPATH)[1:]]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题