简体   繁体   English

Django model 选择不为无效选择引发错误

[英]Django model choice not raising error for an invalid choice

I have an object in Django with a choice field我在 Django 中有一个带有选择字段的 object

class CustomFieldType(models.Model):
    STRING = 'STRING'
    DATE = 'DATE'
    BOOLEAN = 'BOOLEAN'
    NUMERIC = 'NUMERIC'
    EMAIL = 'EMAIL'
    TYPE_CHOICES = (
        (STRING, _('String')),
        (DATE, _('Date')),
        (BOOLEAN, _('Boolean')),
        (NUMERIC, _('Numeric')),
        (EMAIL, _('Email'))
    )
    name = models.CharField(max_length=256)
    field_type = models.CharField(choices=TYPE_CHOICES, default=STRING, max_length=10)
    company = models.ForeignKey('Company')

    class Meta:
        unique_together = ('name', 'company')

    def __unicode__(self):
        return self.name

In my django console在我的 django 控制台中

$> CustomFieldType.objects.create(name='custom_name',field_type='noError',company=mycompany)
<CustomFieldType: custom_name>
$> CustomFieldType.objects.get(name='custom_name').field_type
u'noError'

Why django is not raising an error (ValidationError)?为什么 django 没有引发错误 (ValidationError)? Or Am I missing something?或者我错过了什么?

The choices option is only for pre-populating of form drop down fields; choices选项仅用于预填充表单下拉字段; it does not enforce any validation:它不强制执行任何验证:

If this is given, the default form widget will be a select box with these choices instead of the standard text field.如果给出了这个,默认的表单小部件将是一个带有这些选项的选择框,而不是标准的文本字段。

UPDATE更新

Since django 2.1, setting choices does raise validation errors:从 django 2.1 开始,设置choices确实会引发验证错误:

If choices are given, they're enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field.如果给出了选择,它们由模型验证强制执行,并且默认表单小部件将是带有这些选择的选择框,而不是标准文本字段。

Note that, CustomFieldType.objects.create is not enough.请注意, CustomFieldType.objects.create是不够的。 You need to do something like a model_instance.full_clean() to raise the error.您需要执行类似于model_instance.full_clean()来引发错误。 Just as mentioned in the model validation docs正如模型验证文档中提到的那样

I faced same problem, and I solved it by using save() method instead of create() method, and you must use full_clean() before it.我遇到了同样的问题,我通过使用save()方法而不是create()方法解决了它,并且你必须在它之前使用full_clean() like this:像这样:

x = "your model name"()
x."field" = "value"
.
.
.
"your model name".full_clean(self = x)
"your model name".save(self = x)

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

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