[英]Random Option In Django Drop Down Form
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. 我正在使用模型在Django中创建表单,并且想向一些下拉选项中添加一个Random选项。
Here is a general idea of what I'm working with: 这是我正在使用的基本概念:
models.py 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 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.
当我使用random.choice()创建一个函数并将其推入该函数时,它似乎可以正常工作,但是由于某种原因,总是返回相同的值。
Any help would be greatly appreciated! 任何帮助将不胜感激!
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
. 将
(None,'Random')
到选择集,并在有问题的模型字段上声明default=select_random_gender
和default=select_random_race
以及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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.