0

I've been picking my brain trying to figure this out and so now I turn to the community for help.

I'm using models to create a form in Django and I want to add a Random option to a few of the drop-down choices.

Here is a general idea of what I'm working with:

models.py

Character(models.Model):
    name = models.CharField(max_length=255,unique=True)
    age = models.PositiveIntegerField(default=0)
    gender = models.CharField(max_length=20,choices=creation_choices.GENDERS)
    race = models.CharField(max_length=500,choices=creation_choices.RACE)

creation_choices.py

GENDERS = (
    ('male',"Male"),
    ("female","Female"),
    ("unknown","Unknown"),
)
RACE = (
    ('human','Human'),
    ('elf','Elf'),
    ('dwarf','Dwarf'),
)

What I am trying to do is add a way for users to select Random and it returns one of the other values. I tried a lot of different methods but most returned an error. When I created a function with random.choice() and pushed that through it seemed to work, but for some reason always returned the same value.

Any help would be greatly appreciated!

  • You should try the `choices` argument to the FormField instead of the ModelField, it is more versatile and accepts a callable to generate the choices dynamically. – Klaus D. Oct 10 '17 at 08:24
  • @KlausD. is right. Add a "random" option to the choices of the corresponding form field, and process that extra option in the `clean_fieldname` method of the form. – user2390182 Oct 10 '17 at 08:33

1 Answers1

0

add (None,'Random') to choice sets and on the model-fields in question declare default=select_random_gender and default=select_random_race as well as blank=False, null=False.

declare these functions:

def select_random_gender():
    selection = random.choice(GENDERS)[0]
    return selection if selection else select_random_gender()

def select_random_race():
    selection = random.choice(RACE)[0]
    return selection if selection else select_random_race()
joppich
  • 681
  • 9
  • 20