Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

How to implement `others` for a Django Model Choices-CharField?

$
0
0

I have a Django model that has several CharFields. A lot of these represent information of the type

  1. Item Type 1
  2. Item Type 2
  3. 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

  1. Either the value is in the Choice List
  2. Or it starts with Others: (To indicate that it is a deliberate Other value)

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 choice

Looking 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.


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>