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?
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?
How do I build such a form? I'm swamped. We have to record somewhere what the valid choice is for a specific form:
- Create entries in the database for each question (not scalable)?
- Set it in the session (hacky)?
- Based on user ID (could be predictible)?
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)))
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
.
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…