Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to write Django custom validator

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.

like image 514
Shri Avatar asked Mar 20 '26 16:03

Shri


1 Answers

There are 3 ways, that i know at least:

  1. 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])
    
  2. 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)
    
  3. 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
    
like image 192
alex Avatar answered Mar 22 '26 05:03

alex