我必须在Django文件夹中编写自定义验证器吗?
下面是我有模特的文件夹 /home/shrivatsa555/childrenGK/cgkapp/models.py
我必须仅在1,2和3范围内验证问题难度级别:
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])
我在views.py中编写了一个自定义验证器,但它无效。
答案 0 :(得分:1)
至少我知道有三种方式:
创建一个validators.py文件并在模型中导入验证器并使用它们:
title = models.CharField(max_length=255, validators=[validate_title])
创建一个validators.py文件并在表单中导入验证器并使用它们:
def __init__(self, *args, **kwargs):
super(QuestionsForm, self).__init__(*args, **kwargs)
self.fields['title'].validators.append(validate_title)
您可以在此处创建自定义clean()表单方法并使用您的验证器:
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