Saturday, December 28, 2013

Re: Using <select> input for an IntegerField

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. 

On Saturday, 28 December 2013 17:14:53 UTC-5, Daniel Roseman wrote:
On Saturday, 28 December 2013 20:12:24 UTC, Cody Scott wrote:
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),          }

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b34b5f21-53a6-4b70-91ba-78585fc20df8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment