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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With