In Django form, custom SelectField and SelectMultipleField

后端 未结 5 1623
野趣味
野趣味 2021-01-02 16:11

I am using Django everyday now for three month and it is really great. Fast web application development.

I have still one thing that I cannot do exactly how I want t

5条回答
  •  既然无缘
    2021-01-02 16:47

    I run into this question many times when searching by

    'how to customize/populate Django SelectField options'

    The answer provided by Dimitris Kougioumtzis is quite easy

    Hope it could help somebody like me.

    # forms.py
    from django.forms import ModelForm, ChoiceField
    from .models import MyChoices
    
    class ProjectForm(ModelForm):
        choice = ChoiceField(choices=[
            (choice.pk, choice) for choice in MyChoices.objects.all()])
    
    # admin.py
    class ProjectAdmin(BaseAdmin):
        form = ProjectForm
        ....
    

提交回复
热议问题