Where exactly I have to write the custom validators in Django folder?
Below is the folder where I have my models /home/shrivatsa555/childrenGK/cgkapp/models.py
I have to validate the question difficulty level in the range of 1, 2 and 3 only:
class Questions(models.Model):
Question_Number = models.AutoField(primary_key = True),
Question_Text = models.CharField(max_length = 1000),
Option1 = models.CharField(max_length=500),
Option2 = models.CharField(max_length=500),
Option3 = models.CharField(max_length=500),
Option4 = models.CharField(max_length=500),
Answer = models.CharField(max_length=500),
Difficulty_Level = models.IntegerField(validators=[validate_number])
I have written a custom validator in the views.py but its not working.
There are 3 ways, that i know at least:
Create a validators.py file and import your validators in models and use them likes this:
title = models.CharField(max_length=255, validators=[validate_title])
Create a validators.py file and import your validators in forms and use them like this:
def __init__(self, *args, **kwargs):
super(QuestionsForm, self).__init__(*args, **kwargs)
self.fields['title'].validators.append(validate_title)
You can create custom clean() form method and use your validator here:
def clean(self):
cleaned_data = super(IceCreamOrderForm, self).clean()
title = cleaned_data.get('title', '')
if title in x:
msg = '...'
raise forms.ValidationError(msg)
return cleaned_data
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