I have a Django model that has several CharFields. A lot of these represent information of the type
- Item Type 1
- Item Type 2
- Others
The usual way of defining choices for a CharField is
models.CharField( max_length=255, choices=ChoiceList.choices, # Defining Choices )As you would have guessed, this fails to meet my requirements since I cannot pass it anything(Others) apart from the pre-defined choices.
I cannot discard the choices parameter since I need the model to have the choices information for each field. This will be used to fetch all legal options for a particular field.
I tried using a custom validator function
def validate_choice(value, choices): if value == "Others:": print(value, choices) valid_choices = [choice[0] for choice in choices] if not value.startswith("Others:") and value not in valid_choices: raise ValidationError(f"{value} is not a valid choice")(For simplicity, I defined my logic as
- Either the value is in the Choice List
- Or it starts with
Others:(To indicate that it is a deliberateOthervalue)
And subsequently, I modified the CharField as follows, to use the new Validator Function
models.CharField( max_length=255, choices=IPCSections.choices, validators=[partial(validate_choice, choices=ChoiceList.choices)], )I then noticed that The Choice validation (By Django) happens before the custom validator is called. Which, again leads the the same issue
Others:% is not a valid choiceLooking up in the Django Documentation, I found methods like
model.clean()model.clean_all() etc.I tried overriding these methods, but did not end up with anything useful and the documentation does not cover exactly in what order and when are they called.