Django模型验证器无法创建 [英] Django model validator not working on create

查看:85
本文介绍了Django模型验证器无法创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字段验证器的模型

I have model with a field validator

from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

 class MyModel(model.Model):
     name = models.CharField()
     size = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(10)])

验证器在django管理面板中运行良好,而我尝试输入值大于10,向我显示错误消息确保该值小于或等于10 ,并且不允许保存。

The validator is working well in the django admin panel ,while I try to enter the value more than 10, it's showing me the error message 'Ensure this value is less than or equal to 10' and does not allow to save.

但是,当我在django shell中尝试时,验证器无法正常工作,它允许保存记录,我不知道为什么验证器不会在此处抛出错误消息。

But, when I try in the django shell, the validator is not working, it allows to save the record, I don't know why is the validator not throwing error message here.

>>>form app.models import MyModel
>>>MyModel.objects.create(name="Some Name", size=15)
<MyModel: Some Name>

如果我错过了任何内容或我在这里犯了任何错误,可以请我提出建议。请帮助我解决此问题,对我来说将非常有用。

Can you please suggest me if anything I missed or any mistake i did here. Kindly help me to solve this problem, it will be very greatfull for me, Thanks in advance.

推荐答案

Django验证主要是应用程序级别验证,而不是数据库级别的验证。此外,模型验证不会在模型的保存 / 创建上自动运行。如果要在代码中的特定时间验证值,则需要手动进行。

Django validation is mostly application level validation and not validation at DB level. Also Model validation is not run automatically on save/create of the model. If you want to validate your values at certain time in your code then you need to do it manually.

例如:

from django.core.exceptions import ValidationError
form app.models import MyModel

instance = MyModel(name="Some Name", size=15)
try:
    instance.full_clean()
except ValidationError:
    # Do something when validation is not passing
else:
    # Validation is ok we will save the instance
    instance.save()

更多信息,请参见在django的文档中 https://docs.djangoproject.com/en /1.10/ref/models/instances/#validating-objects

More info you can see at django's documentation https://docs.djangoproject.com/en/1.10/ref/models/instances/#validating-objects

在管理中,由于所有模型形式( ModelForm )将同时执行模型验证过程和表单验证。

In administration it works automatically because all model forms (ModelForm) will run model validation process alongside form validation.

如果您需要验证d ata,因为它来自不受信任的来源(用户输入),因此您需要使用 ModelForm s并仅在表单有效时保存模型。

If you need to validate data because it is coming from untrusted source (user input) you need to use ModelForms and save the model only when the form is valid.

这篇关于Django模型验证器无法创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆