Django widget for a dropdown list

18,176

Solution 1

We need to use forms.Select()

class Meta:
    model=someForm
    fields=['Dropdown']
    widgets = {
      'Dropdown': forms.Select(attrs={'id':'choicewa'}),
      }

Solution 2

The place you marked by ??? is for specifying Field class. If you want to specify proper field class you should use forms.ChoiceField.

Detailed information on widgets and fields:

Share:
18,176
paweloque
Author by

paweloque

My current projects: https://orbit7.ch https://gobugfree.com Follow me on Twitter: @paweloque

Updated on June 27, 2022

Comments

  • paweloque
    paweloque almost 2 years

    Which django widget must be used for a dropdown list? I already have a model which provides a dropdown list. It is, however, necessary to customize the corresponding form element (text and error msg text) and it becomes necessary to specify the widget.

    Here is the Model:

    class ClientDetails(models.Model):
        paymentType = models.CharField(max_length=4, verbose_name='Zahlungsart', choices=PAYMENT_TYPES)
    

    And the Form:

    class ClientDetailsForm(ModelForm):
        paymentType = forms.???(label='Zahlungsart', error_messages={'required': (u'Waehlen Sie die Zahlungsart!'), 'invalid': (u'Waehlen Sie die Zahlungsart!')})
    
  • paweloque
    paweloque almost 13 years
    Ok, that works. Now the field has the first choice preselected instead of showing an unselected option (model => '-----') which then fails to validate if not changed. How to achieve model like behavior with the '----'?
  • Fathy
    Fathy almost 4 years
    this actually worked like charm but dropdown is a such disturbing name for form variable