Using <select> input for an IntegerField

104 views
Skip to first unread message

Cody Scott

unread,
Dec 28, 2013, 3:12:24 PM12/28/13
to django...@googlegroups.com
I have a model with an IntegerField and I would like to display the model form for it with a <select> input.

With the following code I get an error :
'ChoiceField' object has no attribute 'is_hidden'

Here is a minimal django 1.6.1 project with the problem. https://github.com/Siecje/choice_widget/


class Education(models.Model):
    school = models.CharField(max_length=255)
    start_year = models.IntegerField()
    end_year = models.IntegerField()
    degree = models.CharField(max_length=255, null=True, blank=True)

    def __unicode__(self):
        display_txt = '%s, (%s - %s)' % (self.school, self.start_year, self.end_year)
        return display_txt


class EducationForm(forms.ModelForm):

    class Meta:
        model = Education
        fields = ['school', 'start_year', 'end_year', 'degree']
        widgets = {
            #'start_year': forms.TextInput(attrs={'placeholder': '2005'}),
            #'end_year': forms.TextInput(attrs={'placeholder': '2009'}),
            'start_year': forms.ChoiceField(choices=YEAR_CHOICES),
            'end_year': forms.ChoiceField(choices=YEAR_CHOICES),
        }

Daniel Roseman

unread,
Dec 28, 2013, 5:14:53 PM12/28/13
to django...@googlegroups.com
That's not what the `widgets` dict is for. ChoiceField is a field, not a widget, hence the name. If you want to override the field, do it at class level:

class EducationForm(forms.ModelForm):
    start_year = forms.ChoiceField(choices=YEAR_CHOICES)
    end_year = forms.ChoiceField(choices=YEAR_CHOICES)

    class Meta:
        model = Education
        fields = ['school', 'start_year', 'end_year', 'degree'] 

--
DR.

Cody Scott

unread,
Dec 28, 2013, 5:31:33 PM12/28/13
to django...@googlegroups.com
There should be a <select> widget to use in the 'widgets' dict. I was able to override the default of number field with a text field with the lines that are commented out. 
Reply all
Reply to author
Forward
0 new messages