If I want a CharField with only one digit is this the way to write the model
variable = model.CharField(max_length=1)
Or if you only have one Char it is a differnet field?
Thanks!
If I want a CharField with only one digit is this the way to write the model
variable = model.CharField(max_length=1)
Or if you only have one Char it is a differnet field?
Thanks!
If there is only one digit (integer) being used,
You can take a look at:
PositiveSmallIntegerField or SmallIntegerField
variable = model.CharField(max_length=1)
This is perfectly fine. But as @Ilian Iliev noted it might be a good idea to tighten it up with choices
CHOICES = (('1', '1'), ..., ('10', '10')) # Simplified; you may want to add more, auto generate this list etc.
variable = model.CharField(max_length=1, choices=CHOICES)
You can also switch to an Integer field
CHOICES = ((1, '1'), ..., (10, '10'))
variable = model.PositiveIntegerField(choices=CHOICES)
If you want to avoid the hideous drop-down selection widget that gets generated for choice fields, you can do this.
Model:
variable = model.CharField(max_length=1)
Form:
def clean_variable(self):
data = self.cleaned_data['variable']
if data not in string.digits:
raise forms.ValidationError("Not a digit")
return data
Use IntegerField and the clean method that S.Lott show to check is value between 0 and 10