Django“动态"验证表 [英] Django "dynamic" verification form
问题描述
我正在尝试在Django中创建一个验证表单,该表单向用户提供选择列表,其中只有一个是有效的.
I'm trying to create a verification form in Django that presents a user with a list of choices, only one of which is valid.
例如,对于最喜欢比萨饼配料包括菠萝和羊乳干酪的用户,
For example, for a user whose favourite pizza toppings includes pineapple and roquefort—
您最喜欢的比萨馅料是什么?
What is your favourite pizza topping?
- 火腿
- 菠萝
- 凤尾鱼
- Ham
- Pineapple
- Anchovie
每次选择时都应是随机的,顺序和值均应随机选择,但始终有一个有效答案.例如,如果用户刷新页面,则表单可能是-
The choices should be random every time, in both order and values, but always have one valid answer. For example, if the user refreshes the page, the form might be—
您最喜欢的比萨馅料是什么?
What is your favourite pizza topping?
- Mozarella
- 火腿
- 羊乳干酪
- Mozarella
- Ham
- Roquefort
如何构建这样的表格?我被淹没了.我们必须在某处记录特定形式的有效选择是什么:
How do I build such a form? I'm swamped. We have to record somewhere what the valid choice is for a specific form:
- 在数据库中为每个问题创建条目(不可扩展)?
- 在会话中设置它(hacky)吗?
- 基于用户ID(可以预测)吗?
编辑-我们确实将比萨饼浇头列表存储在数据库中-
Edit—We do store the list of pizza toppings in the database—
class UserProfile(Model):
favourite_pizza_toppings = ManyToManyField(PizzaTopping)
我想要的是一种形式,例如-
What I want is a form such as—
class QuestionForm(Form):
questions = ChoiceField(choices=(('a', RANDOMLY_CHOSEN_OPTION_A),
('b', RANDOMLY_CHOSEN_OPTION_B),
('c', RANDOMLY_CHOSEN_OPTION_C)))
在每次实例化时,都会从PizzaTopping.objects.all
中随机选择所有RANDOMLY_CHOSEN_OPTION
,在UserProfile.favourite_pizza_toppings
中也只有一个是PizzaTopping
.
Where, each time it's instantiated, all RANDOMLY_CHOSEN_OPTION
are chosen randomly from PizzaTopping.objects.all
, with only one being a PizzaTopping
also in UserProfile.favourite_pizza_toppings
.
不过,当用户发布表单时,我们将需要验证该表单-这很棘手.我们必须以某种方式记录每个实例化形式的有效选择(a
,b
或c
).我们该怎么做?
We'll need to verify the form when the user POSTs it though—and that's the tricky bit. We have to somehow record which is the valid choice (a
, b
, or c
) for each instantiated form. How can we do this?
推荐答案
您将需要以 init 形式的方法来建立选择,否则每次表单元素的选择都将相同页面加载(它们不会改变).
You will need to build up the choices in the the form init method, otherwise the form elements choices will be the same each time the page loads (they won't change).
class QuestionForm(Form):
questions = ChoiceField()
def __init__(self, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
self.fields['questions'].choices = set_up_choices() # function that creates list
clean_questions(self):
# do your validation of the question selection
# here you could check whether the option selected matches
# a correct value, if not throw a form validation exception
return self.cleaned['questions']
这篇关于Django“动态"验证表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!