简体   繁体   English

Model字段类型和Django中类似的验证器之间有什么区别?

[英]What is the difference between a Model field type and a similar validator in Django?

What is the difference between, say, a EmailField and a validator_email ? 例如, EmailFieldvalidator_email什么EmailField And is it a bad idea to use both? 同时使用这是个坏主意吗?

Or for those who perfer code 或对于那些喜欢代码的人

import django.db import models
email = models.EmailField()

vs

import django.db import models
email = models.CharField( max_length=75, validators = validate_email )

From the doc it seems like you could also use validators inside forms but if you already specify a validation restriction inside models.py , then you don't need specify again in the forms , right? 从文档看来,您似乎也可以在forms使用validators ,但是如果您已经在models.py指定了验证限制,那么就不需要在forms再次指定,对吗? So it seems better to me to take care of all of the restriction inside models.py . 因此,对我来说,照顾好models.py内部的所有限制似乎更好。

I suppose the difference is very little, but then you would be violating the DRY principal, which you probably shouldn't do, unless you have a good reason to do it. 我想差别很小,但是除非您有充分的理由这样做,否则您将违反DRY主体,您可能不应该这样做。

If you go to the code base: 如果您转到代码库:

#django.db.fields.__init__.py

class EmailField(CharField):
    default_validators = [validators.validate_email]
    description = _("E-mail address")

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 75)
        CharField.__init__(self, *args, **kwargs)

    def formfield(self, **kwargs):
        # As with CharField, this will cause email validation to be performed
        # twice.
        defaults = {
            'form_class': forms.EmailField,
        }
        defaults.update(kwargs)
        return super(EmailField, self).formfield(**defaults)

As you can see, the model inherits from Charfield, so you lose nothing by using emailfield, where appropriate. 如您所见,该模型继承自Charfield,因此在适当的地方使用emailfield不会造成任何损失。 Furthermore, the default validator is validate_email. 此外,默认的验证器是validate_email。 Additionally you get the description variable already defined for you. 此外,您还将获得已经为您定义的描述变量。 Lastly, on the backend it is already setting max_length for you at '75'. 最后,在后端,已经为您将max_length设置为'75'。 You could of course override this easily enough by defining a max_length in the same way you would when creating a CharField. 您当然可以通过创建max_length的方式(创建CharField时的方式相同)来轻松地覆盖它。

You can see formfields() is returning forms.EmailField from django.forms. 您可以看到formfields()从django.forms返回form.EmailField。

Looking at that, you can see: 看着那,您可以看到:

#django.forms.fields.py
class EmailField(CharField):
    default_error_messages = {
        'invalid': _(u'Enter a valid e-mail address.'),
    }
    default_validators = [validators.validate_email]

    def clean(self, value):
        value = self.to_python(value).strip()
        return super(EmailField, self).clean(value)

However, you would lose any default values that using the EmailField might provide, such as the "correct" error message and the custom clean() method. 但是,您将丢失使用EmailField可能提供的任何默认值,例如“正确”错误消息和自定义clean()方法。

In the end, while it looks small, actually a good bit of work has already been done for you. 最后,尽管看起来很小,但实际上已经为您完成了很多工作。 So, in general, you shouldn't violate the DRY principal unless you have a good reason to do so. 因此,通常,除非有充分的理由,否则您不应该违反DRY主体。

Edit: 编辑:

Regarding the second question, you want the form to validate against whatever criteria you are concerned about, so when you call form.is_valid() it returns True / False when it should and generates the appropriate failure message. 关于第二个问题,您希望表单根据您关注的任何条件进行验证,因此,当您调用form.is_valid()时,它将在应有的情况下返回True / False并生成适当的失败消息。 Otherwise, is_valid() would validate True, and when you model goes to save, it would fail silently, which would be very hard to track down. 否则,is_valid()会验证True,并且当您保存模型时,它将无声地失败,这将很难追踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM