I want to limit the field to values 0-10 in a select widget.
field=models.IntegerField(max_length=10, choices=CHOICES)
I could just write out all the choices tuples from (0,0),(1,1) on, but there must be an obvious way to handle this.
Help is highly appreciated.
IntegerField in Django Forms is a integer field, for input of Integer numbers. The default widget for this input is NumberInput. It normalizes to a Python Integer. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided.
Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.
IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise.
@Raphael In a migration, an auto_created model gets created by the AddField operation for the ManyToManyField -- it does not exist as a separate model, only as part of the model that defines the m2m field.
IntegerField in Django Forms is a integer field, for input of Integer numbers. The default widget for this input is NumberInput. It normalizes to a Python Integer.
IntegerField in Django Forms is a integer field, for input of Integer numbers. The default widget for this input is NumberInput. It normalizes to a Python Integer. It uses MaxLengthValidator and MinLengthValidator if max_length and min_length are provided. Otherwise, all inputs are valid.
Values from 1 to 32767 are safe in all databases supported by Django. Like an IntegerField, but only allows values under a certain (database-dependent) point. Values from -32768 to 32767 are safe in all databases supported by Django.
If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today () For DateTimeField: default=timezone.now - from django.utils.timezone.now () The default form widget for this field is a DateInput.
Use a Python list comprehension:
CHOICES = [(i,i) for i in range(11)]
This will result in:
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10,10)]
As well as @Torsten has mentioned, you could improve it by:
field = models.IntegerField(choices=list(zip(range(1, 10), range(1, 10))), unique=True)
But remember this will gives you from 1 to 9. Put range (1,11) if you want until 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With