Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force CharField's Choices

I have few models.CharField objects in my Model, with the choices attribute.

This is working great as far as the GUI is concerned, But I want to block values other than these specified in the choices attribute in the code itself (to protect myself from bugs).

Is there a way to raise an exception (I believe it'll be a ValueError) when trying to save a string which is not in the choices list?

like image 902
iTayb Avatar asked Sep 11 '25 14:09

iTayb


1 Answers

You could override the save method of your model to raise your own exception:

class MyModel:

    MY_CHOICES = (
        # choices here
    )

    myfield = models.CharField(max_length=100, choices=MY_CHOICES)

    def save(self, *args, **kwargs):
        choice = self.myfield
        if not any(choice in _tuple for _tuple in self.MY_CHOICES):
            raise ValueError('An error message.')
        super(MyModel, self).save(*args, **kwargs)
like image 79
birophilo Avatar answered Sep 14 '25 08:09

birophilo