In my application models.py I have these fields:
order_by = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(10)])
start_year = models.PositiveSmallIntegerField(validators=[MinValueValidator(datetime.date.today().year - 50), MaxValueValidator(datetime.date.today().year + 1)])
The default widget for these fields is a NumberInput. What I want is a select with options 1 to 10 and 1972 to 2023. I read through a lot of docs and tutorials which solve this issue in many, sometimes complex, ways.
I just wonder isn’t there a simple way to solve this in Django.
I had a look at the IntegerRangeField class of PostgreSQL specific model fields, however, that would make my application dependent, wouldn’t it?
Kind regards,
Johanna
You can select which widget to use for a form field. (As you’ve identified, the number input is just the default.)
You could set up your form to use a select widget for those fields, where the choices are the ranges you’ve identified.
See Widgets | Django documentation | Django to get started.
Hi Ken,
Thanks for your reply. I was a bit confuse by the difference between model fields and form fields.
models.PositiveSmallIntegerField() doesn’t have a widget argument.
forms.IntegerField() does, however, setting up the widget in my form, didn’t render the options of the select.
I opted for using choices=YEAR_CHOICES and calling a function year_choices which uses a for i in range() and returns YEAR_CHOICES
Kind regards,
Johanna
The model fields are a Python representation of a database table.
A form field is a Python representation of an HTML form.
Your code (directly or indirectly) ties the two together.
If you want the form to use a select list, then it’s a ChoiceField, not an IntegerField. You would use the ChoiceField to allow for an entry of a selection from a list in your form.
(The precise mechanics of this depends upon the specifics of your form.)