I have a form that is using NumberInput
widget to accept a rating for a Song from the user. The number should be between 0-5. My Song model has a MaxValueValidator
but I want the NumberInput
widget to show options only from 0-5.
Asked
Active
Viewed 4,823 times
5

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129

Darshan Chaudhary
- 2,093
- 3
- 23
- 42
-
So what does it do currently? what isn't working? – Sayse May 04 '16 at 10:12
-
Currently, it imposes no upper limit on the number it accepts. Only after I submit the form, does the validator kick in and raise an error which is displayed by the form asking the user to enter between 0-5 – Darshan Chaudhary May 04 '16 at 10:14
-
Thats what the validator is for, server side validation, if you want client side validation you need to write that. Django can't help you there – Sayse May 04 '16 at 10:19
-
1Isn't there any attribute I can modify for the widget displayed so that it shows numbers only till 5? Something like : `form.fields['rating'].widget.max_value=5` – Darshan Chaudhary May 04 '16 at 10:21
-
No because django doesn't handle client side validation – Sayse May 04 '16 at 10:26
-
@Sayse, client does handle required client side validation – run_the_race Aug 25 '21 at 12:07
2 Answers
11
In your form you can add min and max value which atleast shows the user the value should be between the limits.
rating = forms.CharField(label='Rating', widget=forms.TextInput(attrs={'min':1,'max': '5','type': 'number'}))

Suresh Jaganathan
- 537
- 5
- 10
-
This also restricts the widget to display only upto `5`. Exactly what I was looking for. – Darshan Chaudhary May 04 '16 at 11:02
2
As shown below, by setting "max"(for maximum number), "min"(for minimum number) to "forms.NumberInput()", you can do what you want to do:
class SongForm(forms.ModelForm):
class Meta:
widgets = {
'rate': forms.NumberInput(attrs={
'max': '5', # For maximum number
'min': '0', # For minimum number
}),
}

Super Kai - Kazuya Ito
- 22,221
- 10
- 124
- 129