Django models choices

42 views
Skip to first unread message

Amine Yaiche

unread,
Mar 21, 2016, 7:54:43 AM3/21/16
to Django users
Hi everyone,

Given a field in a model that uses choices:

CHOICES = (
   
(0, "choice_0"),
   
(1, "choice_1")
)

foo
= models.IntegerField(choices=CHOICES)


If i put a value other than 0 or 1, django will accept it. Is that possible that we instruct Django to accept only values that are mentioned in CHOICES without creating a validator function.

Amandeep Singh

unread,
Mar 21, 2016, 10:12:57 AM3/21/16
to django...@googlegroups.com
The choices don't enforce any default validation. But if you are populating the data from a http call then use ModelForm they show the invalid_choice error message on entering value other than defined choices

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/78d84aa0-506f-4d5c-9590-ef6325c255e0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mike Dewhirst

unread,
Mar 21, 2016, 7:52:33 PM3/21/16
to django...@googlegroups.com
On 21/03/2016 7:29 PM, Amine Yaiche wrote:
> Hi everyone,
>
> Given a field in a model that uses choices:
>
> |
> CHOICES =(
> Â Â (0,"choice_0"),
> Â Â (1,"choice_1")
> )
>
> foo =models.IntegerField(choices=CHOICES)
> |
>
>
> If i put a value other than 0 or 1, django will accept it. Is that
> possible that we instruct Django to accept only values that are
> mentioned in CHOICES without creating a validator function.

Why don't you want to validate in the model?

I find it valuable to put all sorts of validators in the clean() method
and raise a ValidationError to force the user to enter good data. eg.,

if self.foo not in CHOICES:
raise ValidationError("bad foo")

Unless there are special reasons otherwise, I think it is much better in
the model than the form.

Mike


>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To post to this group, send email to django...@googlegroups.com
> <mailto:django...@googlegroups.com>.
> <https://groups.google.com/d/msgid/django-users/78d84aa0-506f-4d5c-9590-ef6325c255e0%40googlegroups.com?utm_medium=email&utm_source=footer>.
Reply all
Reply to author
Forward
0 new messages