Django model choice not raising error for an invalid choice

Question:

I have an object in Django with a choice field

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

$> 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) ? Or Am I missing something ?

Asked By: Guillaume Vincent

||

Answers:

The choices option is only for pre-populating of form drop down fields; 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.

Answered By: Burhan Khalid

UPDATE

Since django 2.1, setting choices does raise validation errors:

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. You need to do something like a model_instance.full_clean() to raise the error. Just as mentioned in the model validation docs

Answered By: Vedant Agarwala

I faced same problem, and I solved it by using save() method instead of create() method, and you must use full_clean() before it. like this:

x = "your model name"()
x."field" = "value"
.
.
.
"your model name".full_clean(self = x)
"your model name".save(self = x)
Answered By: ibda3 . art
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.