How do I use Django's form framework for select options?

后端 未结 4 1073
旧巷少年郎
旧巷少年郎 2021-02-12 15:15

http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Select

Here, it says I can do SELECT widgets. But how do I do that? It doesn\'t show any example on

相关标签:
4条回答
  • 2021-02-12 15:22

    Django 2.0

    Options = [
            ('1', 'Hello'),
            ('2', 'World'),
          ]
    category = forms.ChoiceField(label='Category', widget=forms.Select, choices=sample)
    

    BTW tuple also works as same as list.

    Options = (
            ('1', 'Hello'),
            ('2', 'World'),
         )
    category = forms.ChoiceField(label='Category', widget=forms.Select, choices=sample)
    
    0 讨论(0)
  • 2021-02-12 15:23
    class MyForm(forms.Form):
        CHOICES = (('Option 1', 'Option 1'),('Option 2', 'Option 2'),)
        field = forms.ChoiceField(choices=CHOICES)
    
    print MyForm().as_p()
    
    # out: <p><label for="id_field">Field:</label> <select name="field" id="id_field">\n<option value="Option 1">Option 1</option>\n<option value="Option 2">Option 2</option>\n</select></p>
    
    0 讨论(0)
  • 2021-02-12 15:25
    CHOICES= (
    ('ME', '1'),
    ('YOU', '2'),
    ('WE', '3'),
    )
    select = forms.CharField(widget=forms.Select(choices=CHOICES))
    
    0 讨论(0)
  • 2021-02-12 15:33

    errx's solution was almost correct in my case, the following did work (django v1.7x):

    CHOICES= (
    ('1','ME'),
    ('2','YOU'),
    ('3','WE'),
    )
    select = forms.ChoiceField(widget=forms.Select, choices=CHOICES)
    

    The elements inside CHOICES correspond to ($option_value,$option_text).

    0 讨论(0)
提交回复
热议问题